Skip to content

Error handling in API routes #85

@jamieparkinson

Description

@jamieparkinson

I noticed that in your API routes you're explicitly returning 500 errors - like here, for example

} catch (error) {
console.error(error.message)
res.status(500).json({ error: 'Something went wrong' })
}

A piece of advice that has stuck with me is never to return a 500 on purpose, or at the very least only to return a 500 if you really have no idea what to do with it, as it's for the case that "the server has encountered a situation it does not know how to handle".

You're already using 405 nicely for if the user is doing something other than a PUT - some other descriptive errors might be a 400 if the date isn't in the right format, a 404 if the task with the given ID can't be found, or a 418 if the server is a teapot. Then if you catch an error and you still can't work out what it's about - it's time for a 500! I think the server will return a 500 for you if there's an uncaught error, so you still don't necessarily need to handle it yourselves.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions