我尝试使用 @ControllerAdvice 注释拦截自定义异常。
这是代码:
@ControllerAdvice(basePackages = "{com.ciro.cotroller}")
@RestController
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {TodoNotFoundException.class})
public final ResponseEntity<ExceptionResponse> todoNotFoundException(TodoNotFoundException exception){
ExceptionResponse exceptionResponse = new ExceptionResponse(exception.getMessage(), "custom details");
return new ResponseEntity<ExceptionResponse>(exceptionResponse,HttpStatus.NOT_FOUND);
}
}
这是我的例外:
package com.ciro.exception;
public class TodoNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public TodoNotFoundException() {
throw new RuntimeException("An custom error is raised!");
}
}
但是会返回默认实体响应。