覆盖多个@ControllerAdvice类中的异常

时间:2019-02-21 17:55:43

标签: spring spring-boot

我为一个控制器有两个ControllerAdvice类。

@RestController
@RequestMapping("/student")
public class StudentRestController {
}

第一控制者建议

@ControllerAdvice(assignableTypes = {
        StudentRestController.class
})
public class StudentRestExceptionHandler {

    @ExceptionHandler(StudentNotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseDto studentNotFoundException(StudentNotFoundException e) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.setStatus(ResponseDtoStatus.ERROR);
        responseDto.setMessage(String.format("Student [%s] not found", e.getId()));
        return responseDto;
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    public void accessDeniedException(AccessDeniedException e) {

    }
}

第二个控制器建议是一个通用的控制器建议

@ControllerAdvice(assignableTypes = {
        StudentRestController.class
})
public class GeneralRestExceptionHandler {

    @ExceptionHandler(StudentNotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseDto studentNotFoundException(StudentNotFoundException e) {
        ErrorDto errorDto = new ErrorDto();
        errorDto.setStatus(ResponseDtoStatus.ERROR);
        errorDto.setMessage(String.format("Student [%s] not found", e.getId()));
        return errorDto;
    }
}

我想同时使用基于覆盖的两个控制器建议,如果未在最高顺序建议中映射任何异常,则应从最低优先顺序中选择,这可能吗?

例如,如果我要使用GeneralRestExceptionHandler中的StudentNotFoundException,并且同时使用AccessDeniedException,则应映射到StudentRestExceptionHandler。

我可以同时使用两个ControllerAdvices吗? 我尝试使用Order,但没有用。

0 个答案:

没有答案
相关问题