Saturday, 3 March 2018

How to use local exceptional handler in a Controller ?


Inside controller, provide specific methods for exception handling.
  • Define it using @ExceptionHandler annotation and provide exception class to handle.
  • Use exception object inside exception handler.
  • Return HTTP status and error message in response body using ResponseEntity

EXAMPLE
@Component
@RequestMapping("emp")

public class EmpController {


    @Resource
    private EmployeeRepository employeeRepository;

    @GetMapping
    public ResponseEntity<List<Employee>> getAllEmp() {
        return ResponseEntity.ok((List<Employee>) employeeRepository.findAll());
    }


    @PostMapping
    public ResponseEntity<Employee> emp(@RequestBody Employee emp) {
        return ResponseEntity.ok(employeeRepository.save(emp));
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exceptionHandler(final Exception exception) {
        System.out.println("Exception handler inside controller...");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid data");
    }

}

Whenever any of the method inside controller throws the specific exception, this exception handler will be called.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.