我正在使用 Spring @ControllerAdvice 来处理异常
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { DataIntegrityViolationException.class})
@ResponseBody
public ResponseEntity<String> unknownException(Exception ex, WebRequest req) {
return new ResponseEntity<>(ex.getCause().getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
我遇到的问题是当异常发生时(当我通过 swagger 发送请求时),我没有收到预期的异常消息,但是:
{"error": "no response from server"}
Response Code : 0
Response Body : No Content
在debug模式下可以清楚的看到调用了@ExceptionHandler
注解的方法
我尝试了方法返回类型、@ResponseBody
、@ResponseStatus
注释和其他一些我想到的东西,但似乎我只得到了一些当我返回没有正文的 ResponseEntity
时的非空响应,例如
ResponseEntity.noContent().build()
或
ResponseEntity.ok().build()
在这种情况下,我会得到正确的 http 代码和一些 header
请指出我做错了什么
- Spring 版本 4.3.9
- Spring Boot 版本 1.5.4
提前致谢
UPD
我继续试验,这是对我有用的解决方案。 它非常接近其中一个答案 - 我会将其标记为已接受
简而言之,我只是创建了自己的 dto 类,用我感兴趣的异常详细信息填充实例并直接返回它 我的代码
@ExceptionHandler(value = { DataIntegrityViolationException.class})
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ExceptionDetailHolder unknownException(Exception ex, WebRequest req) {
final Throwable cause = ex.getCause();
return new ExceptionDetailHolder("Error interacting with the database server",
cause.getClass() + ":" + cause.getMessage(),
cause.getCause().getClass() + ":" + cause.getCause().getMessage()
);
}
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
private class ExceptionDetailHolder {
private String message;
private String exceptionMessage;
private String innerExceptionMessage;
}
结果(根据评论者的要求,还显示了 ex.getMessage 和 ex.getCause().getMessage() 的内容):
{
"message": "Error interacting with the database server",
"exceptionMessage": "class org.hibernate.exception.ConstraintViolationException:could not execute statement",
"innerExceptionMessage": "class com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Column 'allow_copay_payments' cannot be null"
}
最佳答案
我处理异常的方式如下所示,我找到特定的异常,然后在这种情况下创建我自己的类对象 ValidationErrorDTO,然后在该类 (ValidationErrorDTO) 中填充必填字段:
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseEntity<ValidationErrorDTO> processValidationIllegalError(HttpMessageNotReadableException ex,
HandlerMethod handlerMethod, WebRequest webRequest) {
Throwable throwable = ex.getMostSpecificCause();
ValidationErrorDTO errorDTO = new ValidationErrorDTO();
if (throwable instanceof EnumValidationException) {
EnumValidationException exception = (EnumValidationException) ex.getMostSpecificCause();
errorDTO.setEnumName(exception.getEnumName());
errorDTO.setEnumValue(exception.getEnumValue());
errorDTO.setErrorMessage(exception.getEnumValue() + " is an invalid " + exception.getEnumName());
}
return new ResponseEntity<ValidationErrorDTO>(errorDTO, HttpStatus.BAD_REQUEST);
}
关于java - 除非正文为空,否则 Spring @ExceptionHandler 不会返回内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46654485/