繁体   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