有人可以解釋一下擴展 ResponseEntityExceptionHandler 的用途嗎?如果我不擴展 ResponseEntityExceptionHandler GlobalExceptionHandler 正在作業并向客戶端發送回應。
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler{
@ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof UserNotFoundException) {
HttpStatus status = HttpStatus.NOT_FOUND;
UserNotFoundException unfe = (UserNotFoundException) ex;
return handleUserNotFoundException(unfe, headers, status, request);
} else if (ex instanceof ContentNotAllowedException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
ContentNotAllowedException cnae = (ContentNotAllowedException) ex;
return handleContentNotAllowedException(cnae, headers, status, request);
} else {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleExceptionInternal(ex, null, headers, status, request);
}
}
}
@ControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof UserNotFoundException) {
HttpStatus status = HttpStatus.NOT_FOUND;
UserNotFoundException unfe = (UserNotFoundException) ex;
return handleUserNotFoundException(unfe, headers, status, request);
} else if (ex instanceof ContentNotAllowedException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
ContentNotAllowedException cnae = (ContentNotAllowedException) ex;
return handleContentNotAllowedException(cnae, headers, status, request);
} else {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleExceptionInternal(ex, null, headers, status, request);
}
}
}
uj5u.com熱心網友回復:
當人們對 Spring 的默認 ExceptionHandlers 普遍感到滿意時,使用 ResponseEntityExceptionHandler - 除了少數幾個,然后可能會被覆寫。
查看 API 檔案中所有受保護的方法:ResponseEntityExceptionHandler
您的 GlobalExceptionHandler 已經接受任何例外并自定義處理兩個特定例外。
如果你堅持使用ResponseEntityExceptionHandler,可以通過擴展類并實作handleExceptionInternal()來達到類似的效果:
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public handleExceptionInternal() {
...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453528.html
下一篇:錯誤:方法拋出“org.springframework.dao.InvalidDataAccessResourceUsageException”例外
