406 Status on Response when invoking setErrorResul

2019-08-07 18:22发布

I am trying to create a simple Spring RestController that uses RxJava's Observable class to perform async processing. Here is my code:

@RestController
@RequestMapping("/users")
public class UserController {
   @Autowired
   private UserAsyncRepository repository;

   @RequestMapping(value="/{userName}", method=GET)
   public DeferredResult<ResponseEntity<User>> getByUserName(
      @PathVariable String userName) {
      final DeferredResult<ResponseEntity<User>> deferred = 
         new DeferredResult<ResponseEntity<User>>();
      repository
         .findByUserName(userName)    // returns Observable<User>
         .singleOrDefault(null)
         .timeout(1, TimeUnit.SECONDS)
         .subscribe(u -> {
              if(u == null) {
                 deferred.setErrorResult(ResponseEntity.notFound());
              } else {
                 deferred.setResult(ResponseEntity.ok(u));
              }
           }, t -> {
              deferred.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR));
           }
         );
      return deferred;
   }
}

When this method is invoked with a valid userName, I get the response I expect with status 200. When this method is invoked with an invalid userName, the response is 406 instead of 404, which is what I expect. Let me know if you have any idea as to why this is happening.

Thanks in advance for your help.

1条回答
够拽才男人
2楼-- · 2019-08-07 19:12

By passing an instance of an exception to the setErrorResult method of the DeferredResult class, I was able to get the 404 response as expected. Here is my exception class:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;

   public ResourceNotFoundException(String message) {
      super(message);
   }
}

The key is making sure you add the @ResponseStatus annotation to your custom exception class.

HTH.

查看更多
登录 后发表回答