![](/img/trans.png)
[英]How to handle Exception in controller for Spring Boot REST API?
[英]How to handle exception from Spring Data Rest Resource?
我在 Spring Data Rest Web 應用程序中使用@RestResource
。 我想自定義RestResource
404 錯誤。
我知道 ControlerAdvice,處理程序......但它不適用於 RestResource 。
我已經嘗試了很多東西:
我當前的源代碼是:
@RestResource(path="user")
public interface UserRepository extends Repository<User, Long> {
User findById(Long id);
}
——
@EnableWebMvc
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ErrorHandlerController extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
ResponseEntity<?> handleNotFound(ResourceNotFoundException ex) {
ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, "Internal server error");
return new ResponseEntity<>(apiError, apiError.getHttpStatus());
}
}
編輯 1(我的問題不是重復的):
我也嘗試像這樣添加一個新的 RestControllerAdviceHandler (但它不起作用):
@RestControllerAdvice
public class RestControllerAdviceHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
return new ResponseEntity<>(" test ", HttpStatus.NOT_FOUND);
}
}
編輯2(關於spring框架源代碼):
經過對 spring 源代碼的更多研究,我找到了下面的代碼。 似乎如果沒有找到實體,則不會引發異常,RestResource 只是返回了一個新的 ResponseEntity>(HttpStatus.NOT_FOUND))。 也許真的不可能用 RestResource 攔截和自定義 Not Found 錯誤?
/**
* <code>GET /{repository}/{id}</code> - Returns a single entity.
*
* @param resourceInformation
* @param id
* @return
* @throws HttpRequestMethodNotSupportedException
*/
@RequestMapping(value = BASE_MAPPING + "/{id}", method = RequestMethod.GET)
public ResponseEntity<Resource<?>> getItemResource(RootResourceInformation resourceInformation,
@BackendId Serializable id, final PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers)
throws HttpRequestMethodNotSupportedException {
return getItemResource(resourceInformation, id).map(it -> {
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(//
() -> assembler.toFullResource(it));
}).orElseGet(() -> new ResponseEntity<Resource<?>>(HttpStatus.NOT_FOUND));
}
這最終在 Spring Data REST 即將發布的 3.2 版中得到修復。
拋出ResourceNotFoundException
異常,現在可以正確攔截。 您使用@ControllerAdvice
解決方案將起作用。
使用 Spring Boot 2.2.0 M2 和以下 ExceptionHandler 進行測試:
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomRepositoryRestExceptionHandler {
@ExceptionHandler
ResponseEntity<?> handleNotFound(ResourceNotFoundException o_O) {
// Simply re-throw the exception and let the default handling kick in, which will produce a response body.
throw o_O;
}
}
正如評論中已經發布的那樣,問題是https://jira.spring.io/browse/DATAREST-1143 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.