springboot 自定义异常 捕获的异常信息 前端接收到的message为空

  1. 问题复现   如下 
  2. timestamp: "2022-10-11T10:22:37.932+00:00", status: 302, error: "Found",…}
    1. error: "Found"
    2. exception: "com.myblog.exception.blogApiException"
    3. message: ""
    4. path: "/myblog/hello"
    5. status: 302
    6. timestamp: "2022-10-11T10:22:37.932+00:00"
  3.  springboot 2.0以上版本 返回的异常信息 message 为空 需要在配置文件中指定server的异常对象和异常信息,在yml文件中,添加配置 
  4. server:
      error:
        include-exception: true
        include-message: always
  5.  配置后即可正常显示异常对象和异常对象
  6. timestamp: "2022-10-11T10:22:37.932+00:00", status: 302, error: "Found",…}
    1. error: "Found"
    2. exception: "com.myblog.exception.blogApiException"
    3. message: "编号01重复"
    4. path: "/myblog/hello"
    5. status: 302
    6. timestamp: "2022-10-11T10:22:37.932+00:00"
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SpringBoot中,我们可以通过自定义异常来处理业务逻辑中出现的异常情况。以下是实现步骤: 1. 自定义异常类 在项目包中创建一个自定义的异常类,需要继承Exception或RuntimeException。 ``` public class CustomException extends RuntimeException { private int code; private String message; public CustomException(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } ``` 2. 异常处理类 在项目包中创建一个异常处理类,需要使用@ControllerAdvice和@ExceptionHandler注解,通过指定异常类来捕获异常并处理。 ``` @ControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(CustomException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result handleCustomException(CustomException e) { return new Result(e.getCode(), e.getMessage(), null); } } ``` 3. 统一响应对象 在项目包中创建一个统一响应对象类,用于统一封装响应信息。 ``` public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } } ``` 以上就是springboot自定义异常的实现步骤。在业务逻辑中抛出自定义异常即可触发异常处理类中的处理方法,并返回统一响应对象。这样可以统一处理异常并返回规范化的响应信息,方便前端或其他系统的处理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值