Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何处理来自Spring数据Rest资源的异常?_Java_Spring_Spring Boot_Spring Data Rest - Fatal编程技术网

Java 如何处理来自Spring数据Rest资源的异常?

Java 如何处理来自Spring数据Rest资源的异常?,java,spring,spring-boot,spring-data-rest,Java,Spring,Spring Boot,Spring Data Rest,我在SpringDataRESTWeb应用程序中使用@RestResource。我想自定义我的RestResource的404错误 我知道控制建议,handler。。。但是它不适用于RestResource 我已经尝试了很多东西: 使用bean或在application.properties中将setThroweExceptionIfNoHandlerFound设置为true 在application.properties中禁用spring.resources.add mappings=fal

我在SpringDataRESTWeb应用程序中使用
@RestResource
。我想自定义我的
RestResource
的404错误

我知道控制建议,handler。。。但是它不适用于RestResource

我已经尝试了很多东西:

  • 使用bean或在application.properties中将setThroweExceptionIfNoHandlerFound设置为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);

}

这最终在SpringDataREST即将发布的3.2版中得到了修复

抛出一个
ResourceNotFoundException
异常,现在可以正确地拦截该异常。 您使用
@ControllerAdvice
的解决方案将起作用

使用弹簧靴2.2.0 M2和以下例外处理程序进行测试:

@ControllerAdvice
@顺序(有序。最高优先级)
公共类CustomRepositoryRestExceptionHandler{
@例外处理程序
ResponseEntity handleNotFound(ResourceNotFoundException o_o){
//只需重新抛出异常并让默认处理启动,这将生成一个响应体。
投掷o_o;
}
}

正如评论中已经提到的,问题是。

@chrylis我试图将404响应空体转换为结构化json体。有什么想法吗?@supunvyjerathne我们有类似的状态,当找不到实体时,我们想告诉您实体不存在,因为空白404可能对所有业务目的都没有多大意义。有什么建议吗?@shivask没有答案。。。所以,我找到了一个解决办法。。。我创建了一个扩展
org.springframework.web.filter.OncePerRequestFilter
的组件类,并截获了所有主体不以“{”开头的响应。因此,所有不是json格式的请求。然后,我将响应主体替换为json。我结合请求url和状态代码来查找errorMessage。它一点也不完美,但可以工作……希望能有所帮助。看起来它已被标记为错误,并有望在将来得到解决。@J.Marciano感谢您提供的信息!您检查了吗我们的ResponseBodyAdvice是在404上调用的?我不确定。但是如果它是对的,它真的很有趣。我认为ResponseBodyAdvice比OncePerRequestFilter更高级。
@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());
    }

}
@RestControllerAdvice
public class RestControllerAdviceHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        return new ResponseEntity<>(" test ", HttpStatus.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));
    }