我在CustomHandler类中全局处理异常。我可以看到,虽然调试这个类捕获异常,但不抛出它们到客户端。请让我知道我错过了什么…
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ConstraintViolationException.class)
public final ResponseEntity<Object> constraintValidationException(
ConstraintViolationException e) {
List<String> details = new ArrayList<>();
for (ConstraintViolation violation : e.getConstraintViolations()) {
details.add(violation.getMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", details);
return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", details);
return new ResponseEntity(error, HttpStatus.UNPROCESSABLE_ENTITY);
}
创建您自己的特定于应用程序的异常和处理它们。例如:public class MyAppEx extends RuntimeException {}
。捕获exception .class,然后抛出异常:
try {
// something goes wrong
} catch (Exception e) {
throw new MyAppEx("details of the exception");
}
替换:
@ExceptionHandler(MyAppEx.class)
public final ResponseEntity<Object> handleAllExceptions(MyAppEx ex, WebRequest request) {..}