totaljs / framework

Node.js framework
http://www.totaljs.com
Other
4.36k stars 450 forks source link

How can I customize response when schema validation failed #605

Closed ckpiggy closed 6 years ago

ckpiggy commented 6 years ago

The framework default behavior is send http 200 and error message about data validation. I want to response status code 400 and send my customize error message when schema validation failed. What should I do ?

petersirka commented 6 years ago

Hi @ckpiggy, you have several options for it:

config:

default-errorbuilder-status   : 400

Custom ErrorBuilder transformation:

ErrorBuilder.addTransform('custom', function(isResponse) {
    var builder = [];

    for (var i = 0, length = this.items.length; i < length; i++) {
        var err = this.items[i];
        // err.name
        // err.error
        // err.path
        // err.index
        builder.push(err.error);
    }

    // this === ErrorBuilder instance
    this.status = 400;

    return isResponse ? builder.join(';') : builder; 
}, true);

Or directly in the schema:

error.status = 400;
ckpiggy commented 6 years ago

Thank you, @petersirka .