簡體   English   中英

如何處理來自 Spring Data Rest Resource 的異常?

[英]How to handle exception from Spring Data Rest Resource?

我在 Spring Data Rest Web 應用程序中使用@RestResource 我想自定義RestResource 404 錯誤。

我知道 ControlerAdvice,處理程序......但它不適用於 RestResource

我已經嘗試了很多東西:

  • 使用 bean 或在 application.properties 中將 setThrowExceptionIfNoHandlerFound 設置為 true
  • 在 application.properties 中禁用 spring.resources.add-mappings=false
  • 在 ControllerAdvice 上添加 basePackages 或 basePackageClass
  • 擴展 RepositoryRestExceptionHandler (但我無法覆蓋它,因為方法是包私有的)

我當前的源代碼是:

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM