Working with exceptions and errors
Developers should always think through all the corner cases possible and write code to handle all those corner cases. Unfortunately, bugs, exceptions, and errors can still slip into production, leading to our users having a bad experience. We have already learned, in Chapter 9, how test cases can help us catch these errors better in the development phase itself, and to improve the user experience, we should show appropriate error messages whenever something breaks. For example, if the server is expecting name
to be present in the body of the request and it is missing, then we should send an error message explicitly saying name field
is missing
.
Here are a few important points we should follow while handling exceptions and errors:
- Always send the appropriate status code. If the request body is missing certain information, then pass
400
and then pass a message explaining the missing information. - If the error is an authentication error...