ExceptionHandler配合RestControllerAdvice全局处理异常
Java全局处理异常
引言
对于controller中的代码,为了保证其稳定性,我们总会对每一个controller中的代码进行try-catch,但是由于接口太多,try-catch会显得太冗杂,spring为我们提供了全局处理异常的方式
@ExceptionHandler
@RestControllerAdvice
项目构建
项目结构
相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
全局处理异常类
package com.lizi.globalexception.exception;
import com.lizi.globalexception.base.BaseResponse;
import com.lizi.globalexception.enums.HttpCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author lizi
* @description GlobalExceptionHandler
* @date 2022/6/7
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 兜底处理RuntimeException异常
*
* @return BaseResponse
*/
@ExceptionHandler(RuntimeException.class)
BaseResponse baseHandler() {
System.out.println("RuntimeException");
return BaseResponse.fail(HttpCode.SYSTEM_ERROR);
}
/**
* 处理NullPointerException异常
*
* @return BaseResponse
*/
@ExceptionHandler(NullPointerException.class)
BaseResponse nullHandler() {
System.out.println("NullPointerException");
return BaseResponse.fail(HttpCode.NULL_ERROR);
}
/**
* 处理ArithmeticException异常
*
* @return BaseResponse
*/
@ExceptionHandler(ArithmeticException.class)
BaseResponse arithmeticHandler() {
System.out.println("ArithmeticException");
return BaseResponse.fail(HttpCode.ARITHMETIC_ERROR);
}
}
package com.lizi.globalexception.enums;
/**
* @author lizi
* @description HttpCode
* @date 2022/6/7
*/
public enum HttpCode {
SUCCESS(200,"成功"),
NULL_ERROR(414,"空指针异常"),
ARITHMETIC_ERROR(415,"算数异常"),
SYSTEM_ERROR(567,"系统异常");
private int code;
private String msg;
HttpCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
演示效果
- 正常请求时
- 兜底异常被捕获时
- 设定的异常被捕获时
Tips
在编写测试类时 一直报错
javax.servlet.ServletException: Circular view path [queryBattle]: would dispatch back to the current handler URL [/queryBattle] again.
找了好久才发现问题
此处是因为注解使用是@ControllerAdvice
原因是因为springboot底层还是使用的springmvc不加@ResponseBody或者@RestController
返回的是ModeAndView对象,因而报错
本文来自博客园,作者:异世界阿伟,转载请注明原文链接:https://www.cnblogs.com/yusishi/p/16353990.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了