Search code examples
javascriptrestexpresserror-handlinghttp-status-codes

Express: Specify HTTP status code when throwing error in service


I want to return the correct HTTP status code to the client when one of my services fails.

Lets assume we have a simple express app where a service getUserById(userId) {...} is called from a controller. The service could fail for several reasons, e.g. an invalid user id, some bug in the code or simply because no user with the given id exists. To return the correct HTTP status code (400, 500 and 404 respectively) I would somehow need to attach it to the error when I throw it from within my service. How do I do this and are there any best practices? Or did I misunderstand something entirely?

So far I have simply done it like this:

throw { message: 'No user with this ID exists', status: 404 }

I do feel however that this is not very maintainable considering that one should only throw standard errors.


Solution

  • You can create an error object and then just add custom properties to it.

    let err = new Error('No user with this ID exists');
    err.status = 404;
    throw err;
    

    Or, I often encapsulate that in a function:

    function error(msg, status = 500) {
        let err = new Error('No user with this ID exists');
        err.status = status;
        throw err;
    }
    

    Or, you can make your own subclass of Error

    class MyError extends Error {
        constructor(msg, status = 500) {
            super(msg);
            this.status = status;
        }
    }
    

    And then use it:

    throw new MyError('No user with this ID exists', 404);