Spring Boot 返回 404 Not Found 的几种方法
假设我们有一个根据 ID 删除某个资源的操作,如果找不到相应 ID 的资源需要返回 404 Not Found。我们可以有以下几种方法来实现这个需求:使用 @ResponseStatus(HttpStatus.NOT_FOUND)使用这个方法,我们需要新建一个异常,然后使用 @ResponseStatus(HttpStatus.NOT_FOUND) 标注它。@ResponseStatus(code
假设我们有一个根据 ID 删除某个资源的操作,如果找不到相应 ID 的资源需要返回 404 Not Found。我们可以有以下几种方法来实现这个需求:
使用 @ResponseStatus(HttpStatus.NOT_FOUND)
使用这个方法,我们需要新建一个异常,然后使用 @ResponseStatus(HttpStatus.NOT_FOUND) 标注它。
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
抛出 ResponseStatusException 异常
使用这个方法不用新建一个异常类。直接抛出异常,并在新建异常的时候设置为 HttpStatus.NOT_FOUND 就好了。
@DeleteMapping("{id}")
public void deleteCustomer(@PathVariable Integer id)
{
try {
var result = this.customerService.findCustomerById(id);
} catch (NotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
this.customerService.deleteCustomer(id);
}
设置 ResponseEntity
我们可以设置返回值为 ResponseEntity,在找不到资源的时候设置 HttpStatus.NOT_FOUND
@DeleteMapping("{id}")
public ResponseEntity<String> deleteCustomer(@PathVariable Integer id)
{
try {
var result = this.customerService.findCustomerById(id);
} catch (NotFoundException e) {
return new ResponseEntity(e.getMessage(), HttpStatus.NOT_FOUND);
}
this.customerService.deleteCustomer(id);
return new ResponseEntity<>(HttpStatus.OK);
}
使用 HttpServletResponse
这个需要我们在 Controller 中相应的方法中增加 HttpServletResponse 参数,如果找不到资源,我们就在 header 中这是 404 Not Found
@DeleteMapping("{id}")
public void deleteCustomer(@PathVariable Integer id, HttpServletResponse servletResponse)
{
try {
var result = this.customerService.findCustomerById(id);
} catch (NotFoundException e) {
servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
this.customerService.deleteCustomer(id);
}
总结
本文介绍了四种让 Spring Boot 返回 404 Not Found 的方法。我个人更喜欢第二种方法,即抛出 ResponseStatusException 的方法。实际上这里介绍的方法,不仅仅局限于 404 Not Found 我们也可以使用这四种方法设置其他的响应状态。
参考链接
https://stackoverflow.com/questions/25422255/how-to-return-404-response-status-in-spring-boot-responsebody-method-return-t
更多推荐
所有评论(0)