You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Framework中HTTP请求异常处理:如何返回指定提示信息?

Spring中处理BookNotPresentException并返回自定义提示的几种方案

方案1:直接在方法内返回ResponseEntity

修改方法返回类型为ResponseEntity<Object>,既能正常返回Book实体,也能在异常时返回错误提示和符合REST规范的404状态码:

@GetMapping("/{id}")
@Override
public ResponseEntity<Object> getById(@PathVariable("id") int id) {
    logger.debug("get book with id: " + id);
    try {
        Book book = bookService.getById(id);
        return ResponseEntity.ok(book);
    } catch (BookNotPresentException e) {
        logger.debug("book not present: {}", e.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("book not present");
    }
}

这种方式改动小,能快速实现需求,同时通过404状态码明确告知客户端资源不存在。

方案2:全局异常处理器(推荐)

这就是你注释里提到的「专用处理器」,把异常处理逻辑抽离,让业务方法更简洁:

  1. 创建全局异常处理类:
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BookNotPresentException.class)
    public ResponseEntity<String> handleBookNotFound(BookNotPresentException e) {
        logger.debug("book not present: {}", e.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("book not present");
    }
}
  1. 简化业务方法,直接抛出异常:
@GetMapping("/{id}")
@Override
public Book getById(@PathVariable("id") int id) {
    logger.debug("get book with id: " + id);
    return bookService.getById(id);
}

所有抛出BookNotPresentException的接口都会自动被统一处理,避免重复编写异常逻辑,代码更易维护。

方案3:返回标准Problem Details(Spring Boot 3+适用)

如果项目基于Spring Boot 3及以上,可以返回符合RFC 7807的标准化错误结构,让API响应更规范:
修改全局异常处理器的返回逻辑:

@ExceptionHandler(BookNotPresentException.class)
public ProblemDetail handleBookNotFound(BookNotPresentException e) {
    logger.debug("book not present: {}", e.getMessage());
    ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
    problemDetail.setTitle("Book Not Found");
    problemDetail.setDetail("book not present");
    return problemDetail;
}

返回的JSON结构会是标准格式:

{
  "type": "about:blank",
  "title": "Book Not Found",
  "status": 404,
  "detail": "book not present",
  "instance": "/books/123"
}

这种方式适合需要统一API错误响应格式的场景,前后端交互更清晰。

内容的提问来源于stack exchange,提问作者Testaastopp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:22:53