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对象,因而报错
标签:return,BaseResponse,ExceptionHandler,HttpCode,lizi,RestControllerAdvice,异常,全局 来源: https://www.cnblogs.com/yusishi/p/16353990.html