简体   繁体   中英

Java Spring exception handling

I have multiple controllers whose exceptions are handled in the ControllerAdvice . All controllers use common exceptions types (like HttpClientException, DBException , etc.). But there is one specific controller which exceptions should be handled differently.

In my current implementation all methods of this specific controller are wrapped with try-catch and throw CustomException in case of any exception. Then, in ControllerAdvice I process this type of exception.

However, I want to handle all exceptions in ControllerAdvice as well as get rid of CustomException and try-catch in controller methods.

Is there any way to find out the source controller name in the exception advice? I could check it and handle the exception differently. Or maybe some other solution exist?

Inside of your controller advice, you can provide Handler for your custom exception as below.

@ControllerAdvice
public class CustomGlobalExceptionHandler {
    @ExceptionHandler(CustomException.class)
    public final ResponseEntity<ApiResponseDTO> manageException(CustomException ex) {
        log.error("Error in CustomException: {}", ex.getMessage(), ex);
        ApiResponseDTO error = ApiResponseDTO.builder()
                .message(ex.getMessage())
                .result(0)
                .build();
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(CustomException1.class)
    public final ResponseEntity<ApiResponseDTO> manageException1(CustomException1 ex) {
        log.error("Error in CustomException1: {}", ex.getMessage(), ex);
        ApiResponseDTO error = ApiResponseDTO.builder()
                .message(ex.getMessage())
                .result(0)
                .build();
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<ApiResponseDTO> manageException1(Exception ex) {
        log.error("Error in Common Exception Handler: {}", ex.getMessage(), ex);
        StackTraceElement[] ste = ex.getStackTrace();
        String className=ste[ste.length - 1].getClassName();
        System.out.println(className);
        if(className.equalsIgnoreCase("com.a")){
            System.out.println("Do A related stuff");
        }else{
            System.out.println("Do B related stuff");
        }
        ApiResponseDTO error = ApiResponseDTO.builder()
                .message(ex.getMessage())
                .result(0)
                .build();
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }

}

As mentioned in last block, you can get class name from where this exception thrown and utilizing that name to branching out your stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM