Java Spring如何为404异常添加自定义消息 解决返回空消息问题
问题描述
如何在抛出404状态码时附带自定义消息"Could not find object with id " + id?
现有实现代码如下:
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Could not find object with id") public class ObjectNotFoundException extends RuntimeException { ObjectNotFoundException(long id) { super("Could not find object with id " + id); } }
该实现返回的响应中message字段为空,返回结果片段如下:
"status": 404, "error": "Not Found", "message": "",
请问需要如何调整才能正确返回自定义的异常消息?
解决方案
问题原因
现有实现出现空message的核心原因有两个:
@ResponseStatus注解中配置了固定的reason参数,Spring会优先使用该固定值生成响应,不会读取异常构造方法中传入的动态消息- Spring Boot默认配置下
server.error.include-message属性值为never,不会把异常的自定义消息暴露到响应体中,避免泄露敏感信息
方案一:调整注解+修改配置(适配默认响应结构)
如果不需要改动Spring Boot默认的错误响应结构,用这个方案即可:
- 删掉
@ResponseStatus注解中的reason参数,修改后异常类代码如下:
@ResponseStatus(code = HttpStatus.NOT_FOUND) public class ObjectNotFoundException extends RuntimeException { public ObjectNotFoundException(long id) { super("Could not find object with id " + id); } }
- 在项目配置文件中开启异常消息暴露:
如果是application.properties文件,添加配置:
server.error.include-message=always
如果是application.yml文件,添加配置:
server: error: include-message: always
调整后响应的message字段就会返回带id的动态自定义消息。
方案二:全局异常处理器(推荐,扩展性更强)
如果需要灵活定制响应字段、统一项目所有异常的返回格式,更推荐用@RestControllerAdvice实现全局异常捕获处理:
- 异常类可以简化为:
public class ObjectNotFoundException extends RuntimeException { public ObjectNotFoundException(long id) { super("Could not find object with id " + id); } }
- 新增全局异常处理类:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ObjectNotFoundException.class) public ResponseEntity<Map<String, Object>> handleNotFoundError(ObjectNotFoundException e) { Map<String, Object> respBody = new HashMap<>(); respBody.put("status", HttpStatus.NOT_FOUND.value()); respBody.put("error", "Not Found"); respBody.put("message", e.getMessage()); // 还可以按需添加时间戳、请求路径等自定义字段 return new ResponseEntity<>(respBody, HttpStatus.NOT_FOUND); } }
这个方案不需要修改额外配置,适配性更强。
内容的提问来源于stack exchange,提问作者Vpmk5
相关产品推荐
相关产品推荐

