개발/spring

[ExceptionHandler] 컨트롤러 에러처리

방푸린 2022. 11. 23. 14:41
반응형

한 @Controller 안에서 발생하는 에러에 대해 별도의 방식으로 처리하고 싶다면, @ExceptionHandler를 해당 컨트롤러 안에 작성하면  된다.

만약 에러를 공통으로 처리하고 싶다면(많은 컨트롤러에 비슷한 @ExceptionHandler가 계속 생긴다면) @ControllerAdvice어노테이션을 단 클래스를 별도로 만들어서 그 안에 @ExceptionHandler를 넣으면 전체적으로 적용된다.

@ExceptionHandler
@ExceptionHandler works at the Controller level and it is only active for that particular Controller, not globally for the entire application.

HandlerExceptionResolver
This will resolve any exception thrown by the application. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes. It does not have control over the body of the response, means it does not set anything to the body of the Response.It does map the status code on the response but the body is null.

@ControllerAdvice
@ControllerAdvice used for global error handling in the Spring MVC application.It also has full control over the body of the response and the status code.

 

1. @ExceptionHandler 가 controller에도 있고 controllerAdvice에도 있다면

controller에 선언한게 우선 적용

 

2. 함수 파라미터로 exception 받으면 함수 내에서 사용 가능

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public ApiResponse handleMappingException() {
  return ApiResponse.ERROR(ApiErrorCode.INVALID_ARGUMENT);
}

@ExceptionHandler(ApiException.class)
@ResponseBody
public ApiResponse handleMoneyException(ApiException e) {  //e 받아서 사용가능
  return ApiResponse.ERROR(e.getMoneyApiErrorCode());
}

 

3. controllerAdvice가 여러개 있다면 순서를 줄 수 있음

@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)

@Order(value = 100)

 

4. 한 controllerAdvice에 여러 ExceptionHandler가 있으면 가장 작은 범위의 exception 으로 선언된 부분이 실행된다.

in case of multiple @ExceptionHandler methods within a @ControllerAdvice, the one handling the most specific superclass of the thrown exception is chosen. 

 

5. spring 4이상에서는 controllerAdvice의 범위를 제한할 수도 있다.

As of Spring 4, @ControllerAdvice can be customized through annotations(), basePackageClasses(), basePackages() methods to select a subset of controllers to assist.
@ControllerAdvice(annotations = RestController.class)

@ControllerAdvice(basePackages = {"com.test.controller.web"})

@ControllerAdvice(basePackages="com.java,hello",
                  basePackageClasses={ Some1.class, Some2.class }, 
                  assignableTypes=SomeController.class
                  annotations=SomeAnnotation.class)
                  
@RestControllerAdvice(basePackages="com.java,hello",
                  basePackageClasses={ Some1.class, Some2.class }, 
                  assignableTypes=SomeController.class
                  annotations=SomeAnnotation.class)
728x90
반응형