Global Exception Handling for Rest Controller in Spring boot

We all know how worst any exception can affect our application. We always advised handling exception so that the application should not stop running.

Global Exception handling for rest controller

In this article, we will learn how to do Global Exception Handling in spring boot for different exceptions.

In Spring boot we can achieve global exception handling by using @ControllerAdvice Annotation. All we need to define java configuration class where we need to define the expected output of different exception we need to handle.

Also Read: Hello World application in spring boot using controller

Let see, How?

We first need to add one class ( actually java configuration class )

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
 
    @ExceptionHandler(value = { MySQLIntegrityConstraintViolationException.class ,DataIntegrityViolationException.class})
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
    	System.out.println(ex.getMessage());
    	
        String bodyOfResponse = "Data Integrity Voilated Please check the input data ";
        return handleExceptionInternal(ex, new Response(false,bodyOfResponse,null , new String(ex.getMessage())), 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
    
    @ExceptionHandler(value = { ConstraintViolationException.class})
    protected ResponseEntity<Object> handleConflict1(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "Data Constraint Voilated";
        return handleExceptionInternal(ex, new Response(false,bodyOfResponse,null , new String(ex.getMessage())), 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }

In Above snippet, what we have added @ControllerAdvice at the class level, which will enable it as ControllerAdvice Class

After that we have extended the ResponseEntityExceptionHandler in our class, This enables use Handle all the Exception occurred for RequestMapping.

@ExceptionHandler above method will tell for which Exception this particular method will be responsible.

After we add this we will be able to handle all the exception we have mentioned in this class without changing any other code.

If you any issue in understanding, let us a comment, If you like this post please share with your friends and family

 

You may also like...

1 Response

  1. November 18, 2018

    […] Global Exception Handling for Rest Controller in Spring boot […]

Leave a Reply

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