Spring AOP【统一异常处理与统一数据格式封装】

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

Spring AOP【统一异常处理与统一格式封装】

🍎一.统一异常处理

统一异常处理:
1、给当前的类上加@ControllerAdvice+@ResponseBody / @RestControllerAdvice.
2、给方法上添加@ExceptionHandler(xxx.class)添加异常返回的业务代码

🍒1.1 实现一个异常方法

@RequestMapping("/user")
@RestController

public class UserController {
    // 算数异常
    @RequestMapping("/index2")
    public String index2() {
        int num = 10/0;
        return "Hello,Index";
    }

当我们没有是实现统一异常处理时页面返回的错误返回给前端是看不懂的,如下:
在这里插入图片描述
所有我们要进行统一异常处理返回给前端

🍒1.2 统一处理异常代码的实现

统⼀异常处理使⽤的是 @ControllerAdvice + @ExceptionHandler 来实现的@ControllerAdvice 表示控制器通知类@ExceptionHandler 是异常处理器两个结合表示当出现异常的时候执⾏某个通知也就是执⾏某个⽅法事件具体实现代码如下:

// 添加 @ControllerAdvice注解来表示@Controller方法增强(这类里异常)通知方法
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice //@ControllerAdvice + @ResponseBody
public class MyExceptionAdvice {

    // 算数异常
    @ExceptionHandler(ArithmeticException.class)
    public HashMap<String,Object> arithemeticExceptionAdvice(ArithmeticException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","算数异常:" + e.getMessage());
        return result;
    }

以上⽅法表示如果出现了异常就返回给前端⼀个 HashMap 的对象其中包含的字段如代码中定义的那样

这时我们就可以通过异常处理来返回一个JSON对象给前端了
在这里插入图片描述

🍒1.3 统一处理所有异常

我们发现在我们处理异常时,需要手动处理多处不同异常情况,这样会使我们消耗大量时间,并且还有些不可控的异常

// 添加 @ControllerAdvice注解来表示@Controller方法增强(这类里异常)通知方法
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice //@ControllerAdvice + @ResponseBody
public class MyExceptionAdvice {

    // 算数异常
    @ExceptionHandler(ArithmeticException.class)
    public HashMap<String,Object> arithemeticExceptionAdvice(ArithmeticException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","算数异常:" + e.getMessage());
        return result;
    }
    
  // 空指针异常
    @ExceptionHandler(NullPointerException.class)
    public HashMap<String,Object> nullPointerExceptionAdvice(NullPointerException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","空指针异常:" + e.getMessage());
        return result;
    }

所有我们可以在处理完特殊异常后,在统一使用Exception 来进行处理

// 添加 @ControllerAdvice注解来表示@Controller方法增强(这类里异常)通知方法
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice //@ControllerAdvice + @ResponseBody
public class MyExceptionAdvice {

    // 算数异常
    @ExceptionHandler(ArithmeticException.class)
    public HashMap<String,Object> arithemeticExceptionAdvice(ArithmeticException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","算数异常:" + e.getMessage());
        return result;
    }
    
  // 空指针异常
    @ExceptionHandler(NullPointerException.class)
    public HashMap<String,Object> nullPointerExceptionAdvice(NullPointerException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","空指针异常:" + e.getMessage());
        return result;
    } 
    
   // 统一处理其他异常
 @ExceptionHandler(Exception.class)
    public HashMap<String,Object> exceptionAdvice(Exception e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",-1);
        result.put("data",null);
        result.put("mag","异常:" + e.getMessage());
        return result;
    }

🍎二.统一格式封装

🍒2.1 实现一个返回数据方法

@RequestMapping("/user")
@RestController

 // 登陆页面
    @RequestMapping("/login")
    public boolean login(HttpServletRequest request,String username, String password){
        boolean result = false;
        // 判断是否在登陆页面输入账号 和 密码
        if (StringUtils.hasLength(username) && StringUtils.hasLength(password)){
            // 验证输入的账号 和 密码 是否正确
            if (username.equals("admin") && password.equals("admin")){
                // 判断输入的账号和密码正确后 建立一个 session对象进行存储
                HttpSession session = request.getSession();
                session.setAttribute("userinfo","userinfo");
                return  true;
            }
        }
        return  result;
    }

🍒2.2 统一处理数据格式封装

统一数据格式封装:
1、给当前类添加@ControllerAdvice。
2、实现 ResponseBodyAdvice重写其方法

package com.example.demo.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice {
    /**
     * 返回一个boolean 值,true 表示放回数据之前对数据进行重写 ,也就会进入 beforeBodyWrite 方法
     *  如果返回 false 表示对结果不进行任何处理,直接返回
     */

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String,Object> result = new HashMap<>();
        result.put("state",1);
        result.put("data",body);
        result.put("msg","");
        return result;
    }
}

🍒2.3 验证格斯封装

在这里插入图片描述
在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring