Spring Boot 返回 404 Not Found 的几种方法

假设我们有一个根据 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

surfirst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值