Learn

In the previous exercise, we discussed the use of @ResponseStatus to apply custom HTTP status codes and reasons to an HTTP response. However, if an error is encountered, we can use ResponseStatusException to exert even more control over the exception handling process.

ResponseStatusException accepts up to 3 arguments:

  • HttpStatus code
  • String reason
  • Throwable cause

We will focus on the HTTP status and reason arguments because they give us insight into whether or not the request was processed successfully and a brief description of what happened if there was an issue.

In a previous exercise, we looked at a method that returns books based on the client’s ISBN submission. Clearly, the method is expecting a number, but if the client’s submission includes a character other than a number, an exception could be thrown.

In the example below, we are accepting the ID from the client as a string and parsing it into an integer. If the parse fails, a NumberFormatException will be thrown. This type of exception may not be so helpful if it is returned to the client. Therefore, we are catching this exception and throwing a new ResponseStatusException that will contain more detailed information. In this way, we have exercised more control over the exception handling process and we can let the user know why the error occurred and/or what they can do to resolve the issue.

@GetMapping("/{id}") public Book isBookAvailable(@PathVariable string id) { if (id.isNumeric()) { int id_int = Integer.parseInt(id) return book.findByID(id_int) } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The ID contained a non-numerical value."); } }

Both the ResponseStatusException class and @ResponseStatus annotation can be used to specify an HTTP status code. ResponseStatusException is used to create specific responses dynamically, while a @ResponseStatus determines the status code for any response returned by the method.

Instructions

1.

The getHeroReportByPostal() method needs a valid postal code for Powersville in order to return an appropriate response. If a postal code is entered for which there are no reports, we want to throw an exception and notify the user there are no results for that postal code.

Throw a ResponseStatusException if there are no SuperReports returned in the getHeroReportByPostalCode() method. The exception should have an HttpStatus of NOT_FOUND and a meaningful reason.

2.

Now let’s test the exception by trying an invalid postal code. Run curl localhost:4001/superHeroes/12345 in the terminal. We should see the exception being thrown along with the custom message we entered in the previous checkpoint.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?