Global Exception Handling using Controller Advice in Spring Boot

Global Exception Handling using Controller Advice in Spring Boot

@ControllerAdvice is an annotation provided by spring to handle exceptions across the whole application. It allow you to handle exception globally and work with your own customized exceptions in an easy way. It works on controllers which means the methods that are annotated with @RequestMapping.

1 Controller Advice

package com.yamicode.snippet.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleException(Exception e){
        return handleResponse(e,HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(MyException.class)
    public ResponseEntity<?> handleMyException(MyException e){
        return handleResponse(e, HttpStatus.FORBIDDEN);
    }

    public ResponseEntity<?> handleResponse(Exception e, HttpStatus httpStatus){
        Map<String, String> response = new HashMap<>();
        response.put("Message", e.getMessage());
        return new ResponseEntity(response, httpStatus);
    }

}

package com.yamicode.snippet.exception;

public class MyException extends Exception {

    public MyException(){
        super("The error is the following");
    }

}

package com.yamicode.snippet.rest;

import com.yamicode.snippet.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExceptionTestingRest {


    @GetMapping("throw/error/{type}")
    public ResponseEntity<?> throwError(@PathVariable() int type) throws Exception {
        if(type==0){
            throw new MyException();
        }else if (type==1){
            throw new Exception();
        }
        return new ResponseEntity(HttpStatus.OK);
    }

}

2 Result

Global Exception Handling using Controller Advice in Spring Boot Example