简体   繁体   中英

How to handle callback error in node.js

I am new to node.js, I have a requirement where i am trying to handle the error that is being returned from the callback method/function. How do i assign the error that is being sent as part of callback to my response payload.

The node module that i am calling to validate swagger supports both callback function as well as Promise.

So how do i assign the err to my response payload. Currently i am just logging to my console, but since we plan to expose this through an API i would like to return the error information in the response payload.

 var express = require('express'); var SwaggerParser = require('swagger-parser'); var myParser = require("body-parser"); var app = express(); var fs = require("fs"); app.use(myParser.urlencoded({extended : true})); app.use(myParser.json()); function errorHandler (err, req, res, next) { res.status(500) res.render('error', { error: err }) } app.post('/v1/swagger/validate',function(request,response){ /**SwaggerParser.validate(request.body, function(err, api) { if (err) { console.error(err); console.log("Inside Error"); } else { console.log("API name: %s, Version: %s", api.info.title, api.info.version); console.log("Inside Success"); } }); **/ SwaggerParser.validate(request.body) .then(function(api) { console.log("API name: %s, Version: %s", api.info.title, api.info.version); }) .catch(function(err) { console.error(err); }); response.end(); }); app.listen(8082); 

You can decide how you want to communicate the error back from your API.

If the error is internal to your server and not something caused directly by a poor API request, then you probably return a 500 status code (internal server error).

response.status(500).end();

If there's something meaningful to communicate back to the other end of the API (like nothing found for the query or a specific validation error), then you have to design what you want that to be. For example, you could be sending back some JSON:

response.json({result: null, msg: "Validation Failed"});

So, it's really up to you what you want your API to return for a given situation. The main point is that you decide what you want that response to be and you send it as the response, even in error conditions. You need to make it a design that makes sense to the consumers of your API so they can clearly tell when they have a proper result and clearly tell when they have an error and if the error is their fault they need to be able to tell why it is their fault based on the response (so they more detail you provide on the issue in the response, the better).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM