SpringBoot2:web开发常用功能实现及原理解析-@ControllerAdvice实现全局异常统一处理

前言

本篇主要针对前后端分离的项目,做的一个统一响应包装、统一异常捕获处理。

1、工程包结构

在这里插入图片描述

2、POM依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

3、Java代码

AppExceptionCodeMsg

//这个枚举类中定义的都是跟业务有关的异常
public enum AppExceptionCodeMsg {

	INVALID_CODE(10000,"验证码无效"),
	USERNAME_NOT_EXISTS(10001,"用户名不存在"),
	USER_CREDIT_NOT_ENOUTH(10002,"用户积分不足");
	;

	private int code ;
	private String msg ;

	public int getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}


	AppExceptionCodeMsg(int code, String msg){
		this.code = code;
		this.msg = msg;
	}

}

AppException

public class AppException extends RuntimeException{

	private int code = 500;
	private String msg = "服务器异常";


	public AppException(AppExceptionCodeMsg appExceptionCodeMsg){
		super();
		this.code = appExceptionCodeMsg.getCode();
		this.msg = appExceptionCodeMsg.getMsg();

	}

	public AppException(int code,String msg){
		super();
		this.code = code;
		this.msg = msg;

	}

	public int getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

}

Resp

import com.atguigu.boot.exception.AppExceptionCodeMsg;

public class Resp<T> {

	//服务端返回的错误码
	private int code = 200;
	//服务端返回的错误信息
	private String msg = "success";
	//我们服务端返回的数据
	private T data;

	private Resp(int code,String msg,T data){
		this.code = code;
		this.msg = msg;
		this.data = data;
	}

	public static <T> Resp success(T data){
		Resp resp = new Resp(200, "success", data);
		return resp;
	}

	public static <T> Resp success(String msg,T data){
		Resp resp = new Resp(200,msg, data);
		return resp;
	}

	public static <T> Resp error(AppExceptionCodeMsg appExceptionCodeMsg){
		Resp resp = new Resp(appExceptionCodeMsg.getCode(), appExceptionCodeMsg.getMsg(), null);
		return resp;
	}
	public static <T> Resp error(int code,String msg){
		Resp resp = new Resp(code,msg, null);
		return resp;
	}

	public int getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

	public T getData() {
		return data;
	}

}

GlobalExceptionHandler

import com.atguigu.boot.bean.Resp;
import com.atguigu.boot.exception.AppException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {


	@ExceptionHandler(value = {Exception.class})
	@ResponseBody
	public <T> Resp<T> exceptionHandler(Exception e){
		//这里先判断拦截到的Exception是不是我们自定义的异常类型
		if(e instanceof AppException){
			AppException appException = (AppException)e;
			return Resp.error(appException.getCode(),appException.getMsg());
		}

		//如果拦截的异常不是我们自定义的异常(例如:数据库主键冲突)
		return Resp.error(500,"服务器端异常");
	}
}

ExpTestController

import com.atguigu.boot.bean.Resp;
import com.atguigu.boot.exception.AppException;
import com.atguigu.boot.exception.AppExceptionCodeMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class ExpTestController {

	@GetMapping("demo")
	public Resp<String> demo(String name){

		if("ok".equals(name)){
			return Resp.success("succ");
		}
		if("err".equals(name)){
			//抛业务相关的异常
			throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS);
		}

		if("errcode".equals(name)){
			throw new AppException(AppExceptionCodeMsg.INVALID_CODE);
		}
		if("0".equals(name)){
			int i=1/0;
		}

		//检查用户积分是否足够,如果不够,就抛出异常
		if("notenough".equals(name)){
			throw new AppException(AppExceptionCodeMsg.USER_CREDIT_NOT_ENOUTH);
		}

		return Resp.success("default");
	}

	@GetMapping("list")
	public Resp<List> list(){
		List<String> list = Arrays.asList("zhangsan","lisi","wangwu");

		return Resp.success(list);
	}
}

好的,很高兴能回答您的问题。 首先,让我们了解一下 @ControllerAdvice 注解。它是 Spring MVC 框架提供的一种全局异常处理机制,可以让我们在一个地方集中处理所有 Controller 抛出的异常。 使用 @ControllerAdvice 注解的类可以包含多个 @ExceptionHandler 注解的方法,每个方法处理不同的异常类型。当 Controller 抛出异常时,Spring 会根据异常类型找到对应的 @ExceptionHandler 方法进行处理。 以下是一个简单的 @ControllerAdvice 示例: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong!"); } @ExceptionHandler(MyCustomException.class) public ResponseEntity<String> handleMyCustomException(MyCustomException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); } } ``` 在上面的例子中,我们定义了两个 @ExceptionHandler 方法,分别处理 Exception 和 MyCustomException 类型的异常。 如果您想要更细粒度地处理异常,可以在 @ExceptionHandler 注解中指定具体的异常类型,如下所示: ```java @ExceptionHandler({IOException.class, SQLException.class}) public void handleIOExceptionOrSQLException() { // ... } ``` 另外,@ControllerAdvice 还支持自定义返回值类型和异常解析器,具体可以参考 Spring 官方文档。 最后,关于统一处理异常,除了使用 @ControllerAdvice,我们还可以使用 Spring Boot 提供的 ErrorController 接口或实现自己的异常处理器。 希望能对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值