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

springboot全局异常捕捉及处理

程序员文章站 2024-03-20 19:55:58
...

        全部异常捕捉,省了每个controller里面try-catch,而且有些异常不一定在controller捕捉,而@RestControllerAdvice,就可以实现全局统一异常的捕捉和处理。以请求参数校验为例,为了校验请求参数是否符合指定的类型、格式、大小等,每个controller层都有类似下面这段代码:

springboot全局异常捕捉及处理

参数校验不符合规范结果返回这段代码不能抛弃,返回前端的结果必须有标准的规范,因此做了这样的妥协。

{
  "code":"1",
  "msg":"success",
  "data":返回的数据
}

如果做了全局异常的捕捉和处理,代码更加整洁,而且省了很多不必要的异常处理

1、ParamExceptionConfig

package com.cn.dl.springbootdemo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * Created by yanshao on 2019-11-06.
 */
@RestControllerAdvice
public class ParamExceptionConfig {
    private static final Logger logger = LoggerFactory.getLogger(ParamExceptionConfig.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String methodArgumentNotValidHandler(MethodArgumentNotValidException exception) {
        logger.error("MethodArgumentNotValidHandler",exception);
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        String msg = fieldErrors.stream().findFirst().map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage())).orElse(null);
        return ResResult.error(msg);
    }

    @ExceptionHandler(RuntimeException.class)
    public String handleRuntimeException(RuntimeException e) {
        logger.error("handleRuntimeException",e);
        return ResResult.error("系统异常");
    }

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        logger.error("handleException",e);
        return ResResult.error("系统异常");
    }
}

2、ResResult:统一返回处理

package com.cn.dl.springbootdemo.config;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * Created by yanshao on 2019-11-06.
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ResResult implements Serializable {

    private static final long serialVersionUID = 4921061998653835814L;

    private static final String errorCode = "0";

    private static final String successCode = "1";

    private String code;

    private String msg;

    private Object data;

    public static String error(String msg){
       return JSONObject.toJSONString(ResResult.builder().code(errorCode).msg(msg).build());
    }

    public static String success(String msg,Object data){
        return JSONObject.toJSONString(ResResult.builder().code(successCode).msg(msg).data(data).build());
    }

}

3、ValidTestController:测试案例

package com.cn.dl.springbootdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.dl.springbootdemo.config.ResResult;
import com.cn.dl.springbootdemo.request.UserOperatorRecordReq;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yanshao on 2019-11-05.
 */
@RestController
@RequestMapping("/user/test")
public class ValidTestController {

    @PostMapping("getRecord")
    public String getUserOperatorRecord(@RequestBody @Valid UserOperatorRecordReq recordReq){
        int i = 0,num = 2;
        List<JSONObject> resultList = new ArrayList<>();
        while (i < num){
            JSONObject json = new JSONObject();
            json.put("date",new Date());
            json.put("operatorType","create");
            i ++;
            resultList.add(json);
        }
        return ResResult.success("success",resultList);
    }

    @PostMapping("getRecordOne")
    public String getUserOperatorRecordOne(@RequestBody @Valid UserOperatorRecordReq recordReq, BindingResult bindingResult){
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if(! CollectionUtils.isEmpty(fieldErrors)){
            String msg = fieldErrors.stream().findFirst().map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage())).orElse(null);
            System.out.println("msg>>>" + msg);
            return ResResult.error(msg);
        }
        int i = 0,num = 2;
        List<JSONObject> resultList = new ArrayList<>();
        while (i < num){
            JSONObject json = new JSONObject();
            json.put("date",new Date());
            json.put("operatorType","create");
            i ++;
            resultList.add(json);
        }
        return ResResult.success("success",resultList);
    }


}

springboot全局异常捕捉及处理

springboot全局异常捕捉及处理