欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot初学习——统一异常处理

程序员文章站 2024-02-19 00:03:10
...

背景

在项目中出现异常时,为了保证返回数据和正常返回的结果数据结构保持一致,需要对异常和返回结果进行格式化处理,现在大部分响应数据的数据结构包括响应码、响应信息和数据对象,具体如下:
SpringBoot初学习——统一异常处理
SpringBoot初学习——统一异常处理

关键步骤

  1. 使用@ControllerAdviceExceptionHandler进行全局异常处理;
  2. 使用自定义的结果处理类封装返回结果

文件结构

SpringBoot初学习——统一异常处理

ResultEnum

使用枚举封装响应码和响应信息

package com.vi.blog.enums;

public enum ResultEnum {
    UNKNOWN_ERROR(-1, "未知错误"),
    SUCCESS(0, "成功"),
    ERROR(1, ""),

    ;
    private Integer code;
    private String message;
    ResultEnum(int code, String message){
        this.code = code;
        this.message = message;
    }

    public Integer getCode(){
        return code;
    }

    public String getMessage(){
        return message;
    }
}

PeopleException

自定义异常

package com.vi.blog.exception;

import com.vi.blog.enums.ResultEnum;

public class PeopleException extends RuntimeException{

    private Integer code;

    public PeopleException(ResultEnum resultEnum){
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }

    public PeopleException(ResultEnum resultEnum, String message){
        super(message);
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

ExceptionHandle

全局的异常处理类

package com.vi.blog.handle;

import com.vi.blog.domain.Result;
import com.vi.blog.enums.ResultEnum;
import com.vi.blog.exception.PeopleException;
import com.vi.blog.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof PeopleException) {
            return ResultUtil.error(((PeopleException) e).getCode(), e.getMessage());
        } else {
            logger.error("【系统异常】{}", e);
            return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMessage());
        }
    }
}

ResultUtil

响应结果处理类

package com.vi.blog.util;

import com.vi.blog.domain.Result;

public class ResultUtil {

    public static Result error(int code, String message){
        Result result = new Result();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static Result success(int code, String message, Object object){
        Result result = new Result();
        result.setCode(code);
        result.setData(object);
        result.setMessage(message);
        return result;
    }
}

Result

响应结果实体类

package com.vi.blog.domain;

public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public Result(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Result() {
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

People

数据对象实体类

package com.vi.blog.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

@Entity
public class People {
    @Id
    @GeneratedValue
    private Integer id;

    @NotNull(message = "年龄不能为空")
    @Min(value = 18, message = "未成年不能入内")
    private Integer age;

    @NotNull(message = "姓名不能为空")
    private String name;

    public People() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Controller

控制器类

package com.vi.blog.controller;

import com.vi.blog.domain.People;
import com.vi.blog.domain.Result;
import com.vi.blog.enums.ResultEnum;
import com.vi.blog.exception.PeopleException;
import com.vi.blog.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class PeopleController {

    private static final Logger logger = LoggerFactory.getLogger(PeopleController.class);

    @PostMapping("/people/add")
    public Result add(@Valid People people, BindingResult bindingResult) {
        logger.info("正在执行方法");
        if (bindingResult.hasErrors()) {
            throw new PeopleException(ResultEnum.ERROR, bindingResult.getFieldError().getDefaultMessage());
        } else {
            return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage(), people);
        }
    }
}