Bootstrap

SpringBoot全局异常处理

在Spring Boot框架中,全局异常处理是一种集中式、统一化的异常处理机制,它允许开发者定义一个全局的异常处理器类,用于捕获和处理应用程序中任何层级抛出的异常。这样的机制极大地简化了异常处理逻辑,提高了代码的可维护性和复用性,减少了在各个业务层分散处理异常所需的代码量。

1.首先创建实体类User和统一返回的实体类ResponseResult

package com.xiaoai.exception.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String username;
    private String password;
}
package com.xiaoai.exception.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseResult<T> {
    private Integer code;
    private String msg;
    private T data;
}

2.创建一个异常类,继承RuntimeException

package com.xiaoai.exception.exception;

public class UsernamePasswordException extends RuntimeException {
    public UsernamePasswordException() {
    }

    public UsernamePasswordException(String msg) {
        super(msg);
    }
}

3.创建异常处理,用来捕获同类型异常

package com.xiaoai.exception.exception.handler;

import com.xiaoai.exception.entity.ResponseResult;
import com.xiaoai.exception.exception.UsernamePasswordException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//这个注解就是用来捕获controller层中的异常
@RestControllerAdvice
public class MyExceptionHeader {

    @ExceptionHandler(UsernamePasswordException.class)
    public ResponseResult<Boolean> usernamePasswordException(UsernamePasswordException e) {
        // 获取异常信息
        System.out.println(e.getMessage());
        return new ResponseResult<>(510, "账号密码错误", false);
    }
}

4.创建controller层来接受请求测试

注:这里为了简单实现功能,我直接在controller层进行判断比对了,实际开发应该从数据库获取数据。

package com.xiaoai.exception.controller;

import com.xiaoai.exception.entity.ResponseResult;
import com.xiaoai.exception.entity.User;
import com.xiaoai.exception.exception.UsernamePasswordException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    // 这里直接创建一个准备好的数据,方便测试,就不去访问数据库了
    private static final User us = new User("tom", "123");

    @PostMapping("/login")
    public ResponseResult<Boolean> login(User user) {
        if (us.getUsername().equals(user.getUsername()) && us.getPassword().equals(user.getPassword())){
            return new ResponseResult<>(200,"success",true);
        }
        throw new UsernamePasswordException();
    }
}

5.使用postman进行测试,分别是账号密码正确和错误两种情况

;