springboot 全局异常统一返回
SpringBoot异常 返回 全局 统一
2023-09-11 14:19:18 时间
不分离使用:@ControllerAdvice+@ExceptionHandler处理全局异常
这种组合适用于前后不分离的
注解:@ControllerAdvice
@Component 作用是将ControllerAdvice 注入到容器中
然后自定义全局异常处理类:仅用于测试使用在实际开发中根据需要指定返回数据,如果是页面,则返回String,如:return "login"
package com.wdz.boot.exception;
import com.wdz.boot.model.ResultMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({NumberFormatException.class})
public ResultMap numberFormatException(NumberFormatException e) {
e.printStackTrace();
System.out.println("数据转换异常:::" + e.getMessage());
return ResultMap.error(e.getMessage());
}
@ExceptionHandler({ArithmeticException.class})
public ResultMap arithmeticException(ArithmeticException e) {
e.printStackTrace();
System.out.println("运算异常:::" + e.getMessage());
return ResultMap.error(e.getMessage());
}
@ExceptionHandler({NullPointerException.class})
public ResultMap nullPointerException(NullPointerException e) {
e.printStackTrace();
System.out.println("空指针异常:::" + e.getMessage());
return ResultMap.error(e.getMessage());
}
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
public ResultMap methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
e.printStackTrace();
System.out.println("参数异常" + e.getMessage());
return ResultMap.error(e.getMessage());
}
// 自定义异常处理
@ExceptionHandler(TestException.class)
public ResultMap testException(TestException e){
return ResultMap.error(e.getMessage());
}
}
自定义异常:
package com.wdz.boot.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// value 指定异常错误状态码,reason 说明异常原因
@ResponseStatus(value = HttpStatus.FOUND,reason = "测试自定义异常")
public class TestException extends RuntimeException {
public TestException(){
}
public TestException(String message) {
super(message);
}
}
如果是前后分离则使用:@RestControllerAdvice+@ExceptionHandler
在服务所在的包路径下创建项目全局异常类
package com.wdz.config;
import com.alibaba.fastjson.JSONObject;
import com.wdz.common.exception.saas.DemoException;
import com.wdz.common.resp.YzxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalException {
@Value("${spring.application.name}")
private String serverName;
@ExceptionHandler(DemoException.class)
public YzxResult handlerException(DemoException demo) {
System.out.println(JSONObject.toJSONString(demo));
return YzxResult.error(serverName+"出错");
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public YzxResult notFount(RuntimeException e) {
return YzxResult.error("运行时异常:" + e.getMessage());
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public YzxResult handleException(HttpRequestMethodNotSupportedException e) {
return YzxResult.error("不支持' " + e.getMethod() + "'请求");
}
}
自定义异常Demo
package com.wdz.common.exception.saas; import lombok.Data; @Data public class DemoException extends RuntimeException { private static final long serialVersionUID = 6304501072268270030L; private String code; private String message; public DemoException(String msg) { this("200", msg); } public DemoException(String code, String msg) { super(msg); this.code = code; this.message = msg; } }
测试控制器
package com.wdz.saas.controller.cli;
import com.wdz.common.exception.saas.DemoException;
import com.wdz.common.resp.YzxResult;
import com.wdz.common.utils.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
@Api(tags = "统一异常测试")
@RestController
@RequestMapping("/cli/course")
public class CliSaasCourseController {
@RequestMapping(value = "demo",method = RequestMethod.POST)
public YzxResult demo(String msg) {
throw new DemoException("11111111111111111");
}
}
结果:
{ "code": "500", "message": "出错", "data": null, "success": false }message 信息可以在全局异常处理时获取,或者固定信息,直接抛不处理message
微服务下,公用全局异常不会抛出指定异常,将全局异常配置放在项目中就可以了,各管各的,有更好的方式,评论中告知谢谢
前后分离的全局异常只是返回结果的不一样,其他的一致
相关文章
- JavaWeb-SpringBoot_(上)腾讯云点播服务之视频的上传-demo
- SpringBoot 2 要不要升级
- 补习系列(15)-springboot 分布式会话原理
- 补习系列(9)-springboot 定时器,你用对了吗
- springboot 定时任务注入线程池
- Atitit springboot 全局异常处理 1.1.@ControllerAdvice 不起作用 public class ExceptionHandle { @ExceptionHand
- Atitit 定时器timer 总结 目录 1. 定时器 循环定时器 和timeout超时定时器1 2. Spring定时器1 2.1. 大概流程1 2.2. 核心源码springboot1
- springboot 实体参数校验 validate 抛出javax.validation.ConstraintViolationException异常 统一处理
- SpringBoot中访问SpringMVC控制器
- 【SpringBoot笔记18】SpringBoot实现统一异常处理、统一结果响应、统一参数校验
- Springboot扩展点之BeanDefinitionRegistryPostProcessor
- SpringBoot 解决主键雪花算法配置
- 【异常】运行SpringBoot程序提示异常,Web server failed to start. Port XXX was already in use.
- 【异常】SpringBoot提示错误:Failed to convert from type [java.lang.String] to type [java.util.Date] for value
- 【SpringBoot2】SpringBoot中配置文件详解
- SpringBoot 异常回滚 事务的使用___Springboot @Transactional 事务不回滚
- Springboot问题解决:javax.servlet.ServletException: Circular view path [login]: would dispatch...
- SpringBoot Profile机制灵活切换环境配置
- Springboot+WebUploader优雅实现超大文件的上传(一)
- 【异常】调用SpringBoot接口时提示错误400 Bad Request No required SSL certificate was sent
- SpringBoot中的profile的使用
- Springboot集成支付宝沙箱支付(完整版)