[英]Spring @ExceptionHandler(Exception.class) always gets called. Why?
[英]@ExceptionHandler(Exception.class) not handling all types of exceptions
我試圖使用@ExceptionHandler(Exception.class)
處理所有類型的異常。 但它並沒有處理所有類型的異常。
當我試圖從郵遞員/瀏覽器訪問錯誤的HTTP方法時,我沒有得到任何響應空白頁面即將到來。
可以請任何人告訴我為什么我沒有得到任何回復或告訴我,如果我在我的代碼中做錯了什么?
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionMessage> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpServletResponse res) {
ExceptionMessage exceptionMessageObj = new ExceptionMessage();
exceptionMessageObj.setStatus(res.getStatus());
exceptionMessageObj.setError(ex.getLocalizedMessage());
exceptionMessageObj.setException(ex.getClass().getCanonicalName());
exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
return new ResponseEntity<ExceptionMessage>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
要么覆蓋ResponseEntityExceptionHandler#handleExceptionInternal()
要么不要擴展ResponseEntityExceptionHandler
。
@ControllerAdvice
上的@Order(Ordered.HIGHEST_PRECEDENCE)
應該在根據這個答案調用ResponseEntityExceptionHandler
之前工作,這表明需要Spring Framework 4.3.7。
使用RequestMapping,您可以為每個Http代碼創建不同的響應。 在這個例子中,我展示了如何控制錯誤並相應地給出響應。
這是具有服務規范的RestController
@RestController
public class User {
@RequestMapping(value="/myapp/user/{id}", method = RequestMethod.GET)
public ResponseEntity<String> getId(@PathVariable int id){
if(id>10)
throw new UserNotFoundException("User not found");
return ResponseEntity.ok("" + id);
}
@ExceptionHandler({UserNotFoundException.class})
public ResponseEntity<ErrorResponse> notFound(UserNotFoundException ex){
return new ResponseEntity<ErrorResponse>(
new ErrorResponse(ex.getMessage(), 404, "The user was not found") , HttpStatus.NOT_FOUND);
}
}
在getId方法中有一點邏輯,如果customerId <10它應該響應客戶ID作為正文消息的一部分但是當客戶大於10時應該拋出異常,在這種情況下服務應該響應ErrorResponse 。
public class ErrorResponse {
private String message;
private int code;
private String moreInfo;
public ErrorResponse(String message, int code, String moreInfo) {
super();
this.message = message;
this.code = code;
this.moreInfo = moreInfo;
}
public String getMessage() {
return message;
}
public int getCode() {
return code;
}
public String getMoreInfo() {
return moreInfo;
}
}
最后我使用了一個特定的Exception來查找“Not Found”錯誤
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.