You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
27 lines
1.6 KiB
27 lines
1.6 KiB
package com.yanzhen.framework.mvc; // 定义包名
|
|
|
|
import com.yanzhen.framework.exception.MyException; // 导入自定义异常类
|
|
import com.yanzhen.utils.Result; // 导入结果处理工具类
|
|
import org.springframework.web.bind.annotation.ControllerAdvice; // 导入Spring MVC的ControllerAdvice注解
|
|
import org.springframework.web.bind.annotation.ExceptionHandler; // 导入Spring MVC的ExceptionHandler注解
|
|
import org.springframework.web.bind.annotation.RequestBody; // 导入Spring MVC的RequestBody注解
|
|
import org.springframework.web.bind.annotation.ResponseBody; // 导入Spring MVC的ResponseBody注解
|
|
|
|
@ControllerAdvice // 标记该类为全局异常处理类
|
|
public class GlobalControllerAdvice {
|
|
|
|
@ExceptionHandler(RuntimeException.class) // 处理所有RuntimeException类型的异常
|
|
@ResponseBody // 将返回值作为HTTP响应体
|
|
public Result handle(RuntimeException exception){ // 定义处理方法,参数为捕获到的异常
|
|
exception.printStackTrace(); // 打印异常堆栈信息
|
|
return Result.fail(exception.getMessage()); // 返回失败的结果对象,包含异常信息
|
|
}
|
|
|
|
@ExceptionHandler(MyException.class) // 处理所有MyException类型的异常
|
|
@ResponseBody // 将返回值作为HTTP响应体
|
|
public Result handle(MyException exception){ // 定义处理方法,参数为捕获到的异常
|
|
exception.printStackTrace(); // 打印异常堆栈信息
|
|
return Result.fail(Result.TOKEN_ERROR,exception.getMessage()); // 返回失败的结果对象,包含错误码和异常信息
|
|
}
|
|
|
|
} |