Exception Handling in Spring Boot REST

Exception Handling in Spring Boot REST | Exception Handling in Spring Boot REST can be done in the following ways:-

  1. Default Error Message (Spring Boot REST) + @ResponseStatus
  2. Customized Error Message – @ControllerAdvice, @ExceptionHandler

Among these customized error message is most commonly used. First, let us see the default error message of Spring Boot REST with @ResponseStatus then we will see the customized error message in Spring Boot REST with @ControllerAdvice and @ExceptionHandler.

Default Error Message (Spring Boot ReST) + @ResponseStatus

In this case, we are using the default message given by BasicErrorController.error() method => (ResponseEntity<T> type–> JSON) format.

Here, we can customize only the Status and message (but not the trace).

{
    "timestamp": "2020-09-03T07:56:41.693+00:00",
    "status": 404,
    "error": "Not Found",
    "trace": ....,
    "message": "EMPLOYEE NOT EXIST 50",
    "path": "/find/50"
}

Create a starter project and add the following dependencies:- Spring web, lombok, Spring Boot DevTools

// model class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private Integer eid;
    private String ename;
}
// Custom Exception
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class EmployeeNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public EmployeeNotFoundException() {
        super();
    }
    
    public EmployeeNotFoundException(String message) {
        super(message);
    }
}
// Rest Controller
@RestController
public class EmployeeRestController {

    @GetMapping("/find/{id}")
    public ResponseEntity<Employee> getOneEmployee(
            @PathVariable Integer id) {
        if(id!=5)
            throw new EmployeeNotFoundException("EMPLOYEE NOT EXIST " + id);
        
        return ResponseEntity.ok(new Employee(id,"SAM"));
    }
}

Customized Error Message – @ControllerAdvice, @ExceptionHandler

In this case, we are defining one new Exception Handler class by using annotations:-

  1. @ControllerAdvice:- At the Handler class level
  2. @ExceptionHandler:- At method Level
  3. ResponseEntity<T>:- Method ReturnType

@ControllerAdvice tells while execution if the application gets any exception in any controller then come to class having @ControllerAdvice. After that based on the Exception type use the appropriate method having @ExceptionHandler.

@RestControllerAdvice was introduced in Spring Framework 4.3 and if we use @RestControllerAdvice then we can remove @ControllerAdvice (from the class level) & @ResponseBody (from the method level).

// exception class
package com.knowprogram.demo.exception;
public class EmployeeNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public EmployeeNotFoundException() {
        super();
    }
    
    public EmployeeNotFoundException(String message) {
        super(message);
    }
}
// model class
package com.knowprogram.demo.model;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    private Integer eid;
    private String ename;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorType {

    private String message;
    private String code;
    private String error;
    private String classType;
}
// exception handler class
//@ControllerAdvice
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(EmployeeNotFoundException.class)
    //@ResponseBody // It converts the response into JSON format
    public ResponseEntity<ErrorType> handleEmpNotFoundEx(
            EmployeeNotFoundException ex) 
    {
        
        return new ResponseEntity<ErrorType>(
                 new ErrorType(
                        ex.getMessage(), 
                        "NO_EMP_FOUND", 
                        "DATA NOT FOUND FOR GIVEN ID", 
                        "Employee"
                ), 
                HttpStatus.BAD_REQUEST);
    }
    
}

Sample Response:-

{
    "message": "Employee Not Exist 5",
    "code": "No EMP Found",
    "error": "Data not found for given ID",
    "classType": "Employee"
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *