1.背景:公司框架 做了全局异常处理,如当前接口定义请求方式是POST,但在调用的时候却使用 GET
后台:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
postman:
{ "timestamp": "2022-04-02T06:35:53.646+00:00", "status": 405, "error": "Method Not Allowed", "message": "", "path": "/sendMessage" }
公司框架返回:
{"status":0,"statusText":"Success","data":null}
1.2 问题出在 明明这个接口报错 ,返回的却是success 得重新处理一下这种异常
2.参考
2.1 SpringBoot中REST API的错误异常处理设计
2.2 Spring Boot Web: 自定义Method Not Allowed响应
2.3 SpringBoot中这样定义全局异常处理器Global Exception Handler
3. debug打断点 发现 公司引用的包 已经定义了全局异常处理,返回的实体类默认 就是 0 success
4.解决方案 代码中写一个异常处理类,并设置其优先级
package ins.business.common.exception; import ins.framework.web.ApiResponse; import ins.framework.web.advice.GlobalExceptionHandler; import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; /** * 自定义异常 */ @ControllerAdvice @Order(1) public class MyControllerAdvice { @ResponseBody @ExceptionHandler(value = Exception.class) public ApiResponse<String> exceptionHandler(Exception ex){ ApiResponse<String> apiResponse = new ApiResponse<>(); apiResponse.setStatus(1); apiResponse.setStatusText(ex.getMessage()); return apiResponse; } }
5.order注解的理解
order注解 主要用来控制配置类的加载顺序:数字越小,越先加载
短信平台 项目启动 加载配置信息到redis 的时候 使用 order注解:实现ApplicationRunner接口,执行顺序按照value值决定,值小先执行
6.设置Oder最高优先级代码
//最高优先级 @Order(Ordered.HIGHEST_PRECEDENCE)