其他分享
首页 > 其他分享> > spring_统一异常处理

spring_统一异常处理

作者:互联网

1 重要注解的介绍

之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑,现在使用Spring能够较好的处理这种问题,核心如下,文章主要关注前两个:
@ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度。
@RestControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开。

public @interface RestControllerAdvice {
	// basePackages属性的别名;允许更简洁的注释声明。
	// 例如,@RestControllerAdvice(“org.my.pkg”)相当于@RestControllerAdvice(basePackages=“org.my.pkg”)
	@AliasFor(annotation = ControllerAdvice.class)
	String[] value() default {};

	// 基本包的数组。将包括属于这些基本包或其子包的控制器; 例如@RestControllerAdvice(basePackages=“org.my.pkg”)或@RestControllerAdvice    
	// (basePackages={“org.my.pkg”,“org.my.other.pkg”}
	@AliasFor(annotation = ControllerAdvice.class)
	String[] basePackages() default {};
}
public @interface ExceptionHandler {
	// 由带注释的方法处理的异常。如果为空,将默认为方法参数列表中列出的任何异常。
	Class<? extends Throwable>[] value() default {};
}

2 案例的引入

1 实体类的编写:

package com.zs.bussiness.pojo;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class OrderParam {
    @NotNull
    private Long goodsId;
    @NotNull
    private Long userId;
    @NotNull
    private Integer amount;
}
package com.zs.bussiness;
import com.fasterxml.jackson.annotation.JsonInclude;
public class JsonResponse<T>{
    //成功
    public static final int SC_SUCCESS = 200;
    //服务端异常
    public static final int SC_SERVER_ERROR = 500;
    //客户端异常
    public static final int SC_CLIENT_ERROR = 400;

    public static final String MSG_SUCCESS = "success";
    public static final String MSG_SERVER_ERROR = "服务端异常,请联系管理员";

    private int code = SC_SUCCESS;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String msg;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data = null;

    public JsonResponse() {
    }
    public int getCode() {
        return code;
 
    public JsonResponse<T> setCode(int code) {
        this.code = code;
        return this;
    }
    public String getMsg() {
        return msg;
    }
    public JsonResponse<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }
    public T getData() {
        return data;
    }
    public JsonResponse<T> setData(T data) {
        this.data = data;
        return this;
    }
    public boolean succeed(){
        return this.code == SC_SUCCESS;
    }
    public static <T> JsonResponse success(T data) {
        return success(data, MSG_SUCCESS);
    }
    public static <T> JsonResponse success(T data, String message) {
        return new JsonResponse().setCode(SC_SUCCESS).setData(data).setMsg(message);
    }
    public static <T> JsonResponse serverError(String message) {
        return new JsonResponse().setCode(SC_SERVER_ERROR).setMsg(message);
    }
    public static <T> JsonResponse serverError() {
        return new JsonResponse().setCode(SC_SERVER_ERROR).setMsg(MSG_SERVER_ERROR);
    }
    public static <T> JsonResponse parameterError(String message) {
        return new JsonResponse().setCode(SC_CLIENT_ERROR).setMsg(message);
    }
}

3 测试一 参数异常

package com.zs.bussiness.controller;
import javax.validation.Valid;
@RestController
public class OrderController {
    @PostMapping("create")
    public JsonResponse createOrder(@Valid OrderParam orderParam){
        return JsonResponse.success(1000L).setMsg("订单创建成功!");
    }
}

在这里插入图片描述

2022-03-20 09:23:55.765  WARN 13652 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.zs.bussiness.JsonResponse com.zs.bussiness.controller.OrderController.createOrder(com.zs.bussiness.pojo.OrderParam): [Field error in object 'orderParam' on field 'amount': rejected value [null]; codes [NotNull.orderParam.amount,NotNull.amount,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [orderParam.amount,amount]; arguments []; default message [amount]]; default message [不能为null]] ]
package com.zs.bussiness;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice("com.zs.bussiness")
public class ControllerExceptionAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult res = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        res.getFieldErrors().forEach((item) -> {
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        return JsonResponse.serverError(errorMap.toString());
    }
}

在这里插入图片描述

4 测试二 业务异常

package com.zs.bussiness.controller;

import com.zs.bussiness.BusinessException;
import com.zs.bussiness.JsonResponse;
import com.zs.bussiness.pojo.OrderParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @PostMapping("/create")
    public JsonResponse createOrder(@RequestBody OrderParam orderParam){
        if (true) {
            throw new BusinessException("扣减库存异常");
        }
        return JsonResponse.success(1000L).setMsg("订单创建成功!");
    }
}
    @ExceptionHandler(value = BusinessException.class)
    public JsonResponse handlerBusinessException(BusinessException e) {
        return JsonResponse.serverError().setMsg("扣减库存异常");
    }

在这里插入图片描述

标签:return,spring,JsonResponse,com,org,import,异常,public,统一
来源: https://blog.csdn.net/zs18753479279/article/details/123591610