Loading

SpringBoot定义优雅全局统一Restful API 响应框架二

这里解决之前留下来的问题,当程序没有正常返回时候

就是程序由于运行时异常导致的结果,有些异常我们可,能无法提前预知,不能正常走到我们return的R对象返回。这个时候该如何处理

在SpringBoot中,可以使用@ControllerAdvice注解来启用全局异常处理。通过使用@ControllerAdvice注解,可以捕获应用程序中的所有异常,从而实现统一的异常处理。如果要自定义异常处理方法,可以使用@ExceptionHandler注解,并指定要捕获的异常类型。这样就可以对指定的异常进行统一的处理。因此,通过@ControllerAdvice和@ExceptionHandler注解的组合,可以实现全局的异常处理。

代码示列

package cn.soboys.springbootrestfulapi.common.exception;


import cn.soboys.springbootrestfulapi.common.resp.R;
import cn.soboys.springbootrestfulapi.common.resp.ResultCodeEnum;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;


/**
 * @author 公众号 程序员三时
 * @version 1.0
 * @date 2023/4/29 00:21
 * @webSite https://github.com/coder-amiao
 * 统一异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 通用异常处理方法
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 指定异常处理方法
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.NULL_POINT);
    }


    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
    }

    /**
     * 处理Get请求中  使用@Validated 验证路径中 单个参数请求失败抛出异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
    }



    /**
     * 自定义异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public R error(BusinessException e) {
        e.printStackTrace();
        return R.failure().message(e.getMessage()).code(e.getCode());
    }

}

异常处理,能够减少代码的重复度和复杂度,有利于代码的维护,并且能够快速定位到BUG,大大提高我们的开发效率。

通过@ControllerAdvice 返回对应错误视图页面,@RestControllerAdvice 返回json 格式的错误api,也可以通过@ControllerAdvice 在方法上加上@ResponseBody返回对应json格式, 类比,controller中返回是一样的

这样暂时解决了,我们上一片文章留下问题

思考

其实这样写,还是不够完美,我们知道我们错误类型有很多种,参数错误也有很多,参数校验还没有达到框架级别,

例如这个是阿里云ECS错误

{
	"RequestId": "5E571499-13C5-55E3-9EA6-DEFA0DBC85E4",
	"HostId": "ecs-cn-hangzhou.aliyuncs.com",
	"Code": "InvalidOperation.NotSupportedEndpoint",
	"Message": "The specified endpoint can't operate this region. Please use API DescribeRegions to get the appropriate endpoint, or upgrade your SDK to latest version.",
	"Recommend": "https://next.api.aliyun.com/troubleshoot?q=InvalidOperation.NotSupportedEndpoint&product=Ecs"
}

这是新浪api的

{
	"request": "/statuses/home_timeline.json",
	"error_code": "20502",
	"error": "Need you follow uid."
}

或者说这样

{
  "result": false,
  "error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}

我们如何在进一步改进呢,

下一篇文章会继续分享,留下你的思考

准备从零做一套自己的开发脚手架模板 ,关注公众 程序员三时

posted @ 2023-05-03 17:59  程序员三时  阅读(94)  评论(0编辑  收藏  举报