[英]Spring @ExceptionHandler does not return content unless body is empty
我正在使用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
我可以在調試模式中清楚地看到調用@ExceptionHandler
注釋的方法。
我已經嘗試了方法返回類型, @ResponseBody
, @ResponseStatus
注釋和一些其他想到的東西,但似乎我只返回一個沒有正文的ResponseEntity
時得到一些非空響應,例如
ResponseEntity.noContent().build()
要么
ResponseEntity.ok().build()
在這種情況下,我得到正確的http代碼和一些標題
請告訴我我做錯了什么
先感謝您
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.