Nuwan.Niroshana
Nuwan.Niroshana

Reputation: 407

NodeJs http status exception handling

I have created nodejs + express application. Now in my application when exception caught errors are send as follows

app.get('/data', (req, res) => {
      if(!req.params.token){
        return res.status(403).send('Access token not provided');
      }

      //do something here
    });

Instead of sending res.status(403).send('Access token not provided'); can I send something like this

exception.js

class Forbidden {
    constructor(message,stack = null){
        this.code = 403;
        this.message = message
        this.stack = stack;
    }
}

app.js

var httpForbidden = require('exception.js');

app.get('/data', (req, res) => {
if(!req.params.token){
    return new httpForbidden ('Access token not provided');
}

//do something here
});

And also how can I caught all exceptions in once place ?

Upvotes: 1

Views: 11582

Answers (4)

Ameya Salagre
Ameya Salagre

Reputation: 793

Below method is deprecated as the boom is changes to @hapi/boom,

https://hapi.dev/family/boom/?v=8.0.1

here you find whole documentation of @hapi/boom library

-----deprecated-------

You can use boom library instead, which provides a set of utilities for returning HTTP errors

HTTP 4xx Errors

Boom.badRequest([message], [data])

Boom.unauthorized([message],[scheme], [attributes])

HTTP 5xx Errors

Boom.badImplementation([message], [data]) - (alias: internal)

Boom.notImplemented([message], [data])

for more api documentation visit here

Upvotes: 1

robertklep
robertklep

Reputation: 203286

You could use something like this:

class httpError {}

class httpForbidden extends httpError {
  constructor(message, stack = null) {
    super();
    this.code = 403;
    this.message = message
    this.stack = stack;
  }
}

app.get('/', (req, res) => {
  if (!req.params.token) {
    throw new httpForbidden('Access token not provided');
  }
  ...
});

app.use((err, req, res, next) => {
  if (err instanceof httpError) {
    return res.status(err.code).send(err.message);
  }
  res.sendStatus(500);
});

This uses an Express error handling middleware that will check if the error that got thrown is an instance of httpError (which would be the superclass of all the HTTP error classes that you'd want to create) and, if so, would generate a particular response according to the code and the message (or generate a generic 500 error response otherwise).

Upvotes: 7

Tabish Rizvi
Tabish Rizvi

Reputation: 367

I like to create a separate function, along with other utility functions ( say in lib.js), which creates a properly formatted JSON response object and selects the appropriate logger to log response depending upon the HTTP status code.

lib.js

var logger = require("./loggger");

module.exports.sendResponse = function (res,code,message,data) {

    if(code<100 || code>599) {
        throw new Error("response cannot be sent. Invalid http-code was provided.");
    }
    var responseLogger = code>=500 ? logger.error : logger.debug;

    var responseObject = {
        "code" : code,
        "message" : message
    };

    if(data) {
        responseObject.data = data;
    }

    responseLogger(responseObject);

    res.status(code).json(responseObject);
};

app.js

var lib = require("./lib");

/*
Relevant Express server code
 */
app.get('/data', function (req,res) {

    if(!req.params.token){
        return lib.sendResponse(res,403,"Access token not provided");
    }

    // Rest of business logic
});

Note : You can write your own logging functionality, but I strongly suggest to build it upon some standard logging library like winston)

Upvotes: 2

rsp
rsp

Reputation: 111316

You can use:

res.code(403).json({message: '...', stack: '...'});

and send whatever you want. But you do it with calling methods on the response object.

And also how can I caught all exceptions in once place ?

Very bad idea. You should handle all errors where they happen so that you can still have some context to handle them in a reasonable way. Otherwise you can just throw exceptions and return 500 errors.

Upvotes: 0

Related Questions