使用@ControllerAdvice统一处理自定义异常

本文介绍了一种在AOP中实现统一异常处理的方法,通过自定义异常类、异常处理器和结果封装,实现了异常信息的JSON格式化返回,便于前端展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近工作中涉及到捕捉AOP方法中抛出的异常。

想针对某一种异常做一个统一的处理器并封装好异常信息以JSON格式交给前端进行提示。

 

主要实现的话有以下几步:

1.编写自定义异常类

package com.laoxu.easyblog.exception;

/**
 * @Description: 未授权异常
 * @Author laoxu
 * @Date 2019/7/3 21:51
 **/
public class UnAuthorizedException extends RuntimeException{
    private static final long serialVersionUID = 1L;

    private String errorCode;
    private String errorMessage;

    public UnAuthorizedException(String errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

 

2.编写异常处理器

package com.laoxu.easyblog.framework;

import com.laoxu.easyblog.exception.UnAuthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description: 异常处理器
 * @Author laoxu
 * @Date 2019/7/3 22:14
 **/
@ControllerAdvice
public class ExceptionsHandler {
    @ResponseBody
    @ExceptionHandler(UnAuthorizedException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
    public Result<String> customGenericExceptionHnadler(UnAuthorizedException exception){ //还可以声明接收其他任意参数
        return ResultUtil.fail(Integer.valueOf(exception.getErrorCode()),exception.getErrorMessage());
    }
}

 

3.包装返回信息

package com.laoxu.easyblog.framework;

/**
 * 返回结果工具类
 *
 * @author xusucheng
 * @create 2018-10-23
 **/
public class ResultUtil {
    public static boolean isOk(Result<?> result){
        return null != result && result.getCode() == ErrorStatus.OK.getCode();
    }

    public static <T> Result<T> ok(){
        return new Result<T>(ErrorStatus.OK);
    }

    public static <T> Result<T> ok(T data){
        return new Result<T>(ErrorStatus.OK.getCode(), ErrorStatus.OK.getMessage(), data);
    }

    public static <T> Result<T> fail(){
        return new Result<T>(ErrorStatus.BAD_REQUEST).fail();
    }

    public static <T> Result<T> status(ErrorStatus status){
        return new Result<T>(status.getCode(), status.getMessage()).fail();
    }

    public static <T> Result<T> fail(ErrorStatus status){
        return new Result<T>(status.getCode(), status.getMessage()).fail();
    }

    public static <T> Result<T> fail(String message){
        return fail(ErrorStatus.BAD_REQUEST.getCode(), message, (T)null).fail();
    }

    public static <T> Result<T> fail(int code, String message){
        return new Result<T>(code, message).fail();
    }

    public static <T> Result<T> fail(int code ,String message, T data){
        return new Result<T>(code, message, data).fail();
    }

    public static <T> Result<T> notfound(){
        return new Result<T>(ErrorStatus.NOT_FOUND).fail();
    }

}

 

4.编写测试controller

package com.laoxu.easyblog.controller;

import com.laoxu.easyblog.exception.UnAuthorizedException;
import com.laoxu.easyblog.framework.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description:
 * @Author laoxu
 * @Date 2019/7/3 22:09
 **/
@Controller
@RequestMapping("/auth")
public class ExceptionController {

    @RequestMapping("/getLoginUser")
    public Result<String> getLoginUser(){
        throw new UnAuthorizedException("403","用户未授权!");
    }
}

 

5.编写测试页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试页</title>
    <script src="../js/jquery.min.js" th:src="@{/assets/js/jquery.min.js}"></script>


</head>
<body>

<button onclick="getLoginUser();">获取用户信息</button>
<script>
    function getLoginUser(){
        $.ajax({
            url: "/blog/auth/getLoginUser",
            type: "GET",
            success: function (result) {
                if (result.success) {
                    alert("获取成功!");
                } else {
                    alert(result.code+":"+result.message);
                }

            }
        });
    }

</script>
</body>
</html>

 

6.测试

 

 

 

 

好的,很高兴能回答您的问题。 首先,让我们了解一下 @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、付费专栏及课程。

余额充值