Resource throwing an exception

Let's create a resource that throws an exception, and send a GET request to it in order to understand how the application reacts to runtime exceptions.

Let's create a dummy service that throws an exception. The following code snippet shows a simple service:

    @GetMapping(path = "/users/dummy-service")
public Todo errorService() {
throw new RuntimeException("Some Exception Occured");
}

Some important things to note are as follows:

  • We are creating a GET service with the URI /users/dummy-service.
  • The service throws ;RuntimeException. We chose RuntimeException to be able to create the exception easily. We can easily replace it with a custom exception ;if needed.

Let's fire a GET request to the preceding service at http://localhost:8080/users/dummy-service using Postman. The response is as shown in the following code:

    {
"timestamp": 1484028119553,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.RuntimeException",
"message": "Some Exception Occured",
"path": "/users/dummy-service"
}

Some important things to note are as follows:

  • The response header has an HTTP status of 500; Internal server error
  • Spring Boot also returns the message with which the exception is thrown

As we can see in the preceding two examples, Spring Boot provides good default exception handling. In the next section, we will focus on understanding how the application reacts to custom exceptions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset