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

Spring Boot自定义异常消息不显示,如何解决?

问题分析与解决方案

你的代码核心问题是将@ExceptionHandler异常处理器注解和业务接口方法(@GetMapping)混在了同一个方法上,Spring无法识别这是一个异常处理逻辑,导致抛出的NotFoundException没有被正确捕获,最终触发了默认的500错误响应。同时,NotFoundException对应的HTTP状态码应该是404 NOT_FOUND,而非500 INTERNAL_SERVER_ERROR。

修复步骤

1. 确保自定义异常类正确

先确认你的NotFoundException是继承自RuntimeException的自定义异常:

public class NotFoundException extends RuntimeException {
    public NotFoundException(String message) {
        super(message);
    }
}

2. 拆分业务方法与异常处理方法

在@RestController类中,把业务接口方法和异常处理方法分开写:

@RestController
public class UserController {

    @Autowired
    private UserRepo userRepo;

    // 业务接口方法:处理查询用户请求
    @GetMapping("userino/{id}")
    public User getUserino(@PathVariable long id) {
        Optional<User> u = userRepo.findById(id);
        if (u.isPresent()) {
            return u.get();
        }
        throw new NotFoundException("Inexistent user " + id);
    }

    // 单独的异常处理方法:捕获当前控制器抛出的NotFoundException
    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleNotFoundError(NotFoundException ex) {
        // 返回自定义错误文本和404状态码
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

如果需要返回结构化的JSON错误响应,可以自定义一个响应体类:

// 自定义错误响应体(可选)
static class ErrorResponse {
    private String errorMessage;

    public ErrorResponse(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}

// 对应的异常处理方法修改为:
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<ErrorResponse> handleNotFoundError(NotFoundException ex) {
    return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.NOT_FOUND);
}

3. 全局异常处理(可选)

如果希望所有控制器的NotFoundException都能被统一处理,可以使用@RestControllerAdvice定义全局异常处理器:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleGlobalNotFoundError(NotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

验证效果

修改后再次访问localhost:8080/userino/3,Postman会返回404状态码,以及你自定义的错误文本:

{
    "errorMessage": "Inexistent user 3"
}

(如果用字符串响应则直接返回文本内容)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:43:25