Skip to content

how to bind custom handler

soomtong edited this page Jul 19, 2015 · 1 revision

extend error handler

sometime u need to make own error handler for custom response messages

u can extend node-restify-validation too.

prepare restifyValidation middleware like below

var restify = require('restify');
var restifyValidation = require('node-restify-validation');

...

bind your custom error handler in restify.use()

  • handleError: middleware.validationError

check out middleware.validationError below

    var server = restify.createServer(options);

    server.use(restifyValidation.validationPlugin({
        errorsAsArray: false,
        handleError: middleware.validationError
        // no errorHandler, use handleError
    }));

...

for more extendable patterns

// request validation error handler
middleware.validationError = function (res, errors) {
    var result = feedback.notAcceptable("validation failed", errors);

    return res.json(result.statusCode, result);
};

feedback.notAcceptable = function (message, data) {
    return feedback.create(406, message, data);
};

feedback.create = function (statusCode, message, data) {
    var result = {
        message: message || undefined,
        data: data || null
    };

    return feedback.init(result, statusCode);
};

feedback.init = function (result, statusCode, message) {
    result.isResult = true;
    result.statusCode = statusCode;
    result.meta = {
        error: http.STATUS_CODES[statusCode] || 'Unknown'
    };

    if (statusCode === 500) {
        result.meta.message = 'An internal server error occurred';
    } else if (result.message) {
        result.meta.message = result.message;
    }

    if (!message && !result.message) {
        message = result.meta.error;
    } else if (result.message) {
        message = result.message;
    }

    if (message) {
        result.message = (result.meta.error + (result.message ? ': ' + result.message : ''));
    }

    return result;
};

make happy nodejs coding with restify and node-restify-validation

Clone this wiki locally