Springboot @ResponseStatus message为null

本文介绍了一种在SpringBoot应用中使用@ResponseStatus注解时遇到的问题:自定义异常message返回为空的情况。针对该问题,文章给出了具体解决方案,即通过在配置文件中设置server.error.include-message为always来确保异常message能够正确返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现象:

代码中我们使用@ResponseStatus要返回自定义的异常message,但是接口返回的message为null

   		if (null == db) {
            throw new NotExist("conductorEnv not exist");
        }
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequest extends RuntimeException{
    public BadRequest(String message, Exception exception) {
        super(message, exception);
    }
    public BadRequest(String message) {
        super(message);
    }
    public BadRequest() {
        super("Bad Request: please check your request body.");
    }
}
{
    "timestamp": 1656905642972,
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/api/v1/workflow/clusters/CID-87/conductor/env/update/CID-787"
}

解决办法

从SpringBoot 2.3+开始,引入了一下新的属性来控制message
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#new-and-noteworthy
在这里插入图片描述
我们要做的是在配置文件中加入

server:
  error:
    include-message: always
### Spring Boot 中处理数值为空的方法 在 Spring Boot 应用程序中,当需要处理可能为空的输入参数时,可以采用多种方法来确保应用程序能够稳定运行并提供有意义的反馈给客户端。 #### 使用 `@RequestParam` 和默认值设置 对于控制器层中的请求参数,可以通过 `defaultValue` 属性为 `@RequestParam` 注解指定一个默认值。这允许即使用户未传递该参数也能有一个合理的回退选项[^2]: ```java @GetMapping("/example") public String exampleMethod(@RequestParam(value = "param", defaultValue = "default") String param) { return "Received parameter value is: " + param; } ``` #### 利用 Hibernate Validator 进行空值校验 为了实现更严格的验证逻辑,推荐使用 Hibernate Validator 提供的一系列约束注解来进行数据有效性检查。例如,在实体类字段上应用 `@NotNull`, `@NotEmpty` 或者其他适合场景需求的注释标签: ```java import javax.validation.constraints.NotEmpty; public class UserRequest { @NotEmpty(message = "Name cannot be empty or null.") private String name; // getters and setters... } ``` 接着可以在 Controller 方法签名处加入 `BindingResult` 参数用于捕获违反上述规则产生的错误信息,并通过自定义的方式返回更加友好的提示消息给前端调用方: ```java @PostMapping("/users") public ResponseEntity<?> createUser( @Validated @RequestBody UserRequest user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { List<String> errors = new ArrayList<>(); bindingResult.getAllErrors().forEach(error -> errors.add(((FieldError) error).getField() + ": " + error.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); } userService.saveUser(user.getName()); return ResponseEntity.ok("Success"); } ``` 针对全局异常处理器方面,考虑到从版本 2.5.x 开始,默认情况下不再暴露详细的异常堆栈跟踪至外部接口响应体内的变化[^1],建议开发者自行配置统一的异常处理机制以便更好地控制 API 输出格式以及安全性考量。 #### 配置全局异常处理器 创建一个新的类继承自 `ResponseEntityExceptionHandler` 并重写相应的方法,从而达到定制化 HTTP 错误码及其伴随描述的目的;另外也可以利用 AOP 方面的知识点围绕特定包下的所有 RESTful 接口实施环绕通知操作完成相同效果。 ```java @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { Map<String, Object> body = new LinkedHashMap<>(); body.put("timestamp", LocalDateTime.now()); body.put("status", status.value()); List<String> errors = ex.getGlobalErrors() .stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); body.put("errors", errors); return new ResponseEntity<>(body, headers, status); } } ``` 以上就是关于如何在 Spring Boot 中处理数值为空情况的一些常见做法介绍。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值