Uddhav Bhagat
Uddhav Bhagat

Reputation: 75

How to deal with errors in ExpressJS rest API

I am confused whether I should just console.log out the error, or should I return the error to my front end. Could someone tell me what the best practice is?

For example, right now, if it is a error with status code 400, I just console log unable to create playlist. So, should I let it be or should I change it to return res.status(400).send(err). What are the pros and cons for both?

        try {
            playlist_id = await create_playlist(req, res, spotifyAPI);
            console.log('created');
        } catch(err) {
            if (err['statusCode'] === 401) {
                req.logout();
                console.log('authentication code reset');
                return res.status(401).send(err);
            }
            else {
                console.log('error - unable to create playlist');
            }
        }

Upvotes: 0

Views: 1476

Answers (3)

mappie
mappie

Reputation: 502

The error handling depends upon specific use cases and a contract is fixed and followed by the APIs. Various response formations could be used for error handling.

  1. Error handling with an appropriate status code. eg: Respond with 404 for conveying that the requested resource does not exist.

  2. Create an error object which shows the details of the error. Custom error codes could be included to handle specific handling on the frontend.

{
   "status": 401,
   "error": "ERR-AUTH-001",
   "message": "Username does not exist",
   "detail": "Ensure that the username entered is correct"
}
  1. Maintain a standard response body from the backend.
{
   "status": 401,
   "errors": [{
      "errorcode": "ERR-AUTH-001",
      "message": "Username does not exist",
   }],
   detail: "Ensure that the username entered is correct"
}

or

{
   "status": 401,
   "success": false,
   "error": {
      "errorcode": "ERR-AUTH-001",
      "message": "Username does not exist",
      "detail": "Ensure that the username entered is correct"
   }
}

You could use the former if various errors are to be reported in a response.

Example: Google standard for Search Ads 360 API

Upvotes: 2

mJehanno
mJehanno

Reputation: 866

Usually, you don't want to send the whole error object to your front as it'll will give some hint to potential hacker, so you want to log the error message on your server (it can be in a file or a log manager like ELK stack or a simple database) and just return a status code to your front. You can then define a "user-friendly" error message in your front.

Exemple : User fail to authenticate giving the right login but the wrong password, you return a 400, your front display 'invalid credentials'

Upvotes: 1

Nicolas Pezet
Nicolas Pezet

Reputation: 21

There is no best practice but if you want your front to have a special behaviour on this error you should return your 400 status code. If not, just log it but your front won't be alerted.

Upvotes: 1

Related Questions