SpringBoot defines an elegant global unified Restful API response framework 2

Here to solve the problems left before, when the program does not return normally

It is the result of the program due to runtime exceptions. We may or may not be able to predict some exceptions in advance, and cannot go to our return R object to return normally. How to deal with this time

In SpringBoot, @ControllerAdviceannotations can be used to enable global exception handling. By using the @ControllerAdvice annotation, all exceptions in the application can be caught to achieve unified exception handling. If you want to customize the exception handling method, you can use @ExceptionHandlerannotations and specify the exception type to be caught. In this way, the specified exception can be handled uniformly. Therefore, global exception handling can be achieved through the combination of @ControllerAdvice and @ExceptionHandler annotations.

code example

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());
    }

}

Exception handling can reduce code repetition and complexity, facilitate code maintenance, and quickly locate bugs, greatly improving our development efficiency.

By @ControllerAdvicereturning the corresponding error view page, @RestControllerAdvicereturn the error api in json format, or add @ControllerAdvicethe method to @ResponseBodyreturn the corresponding json format, analogy, the return in the controller is the same

This is temporarily solved, we left the problem in the last article

think

In fact, writing this way is still not perfect. We know that there are many types of errors, and there are also many parameter errors. The parameter verification has not yet reached the framework level.

For example, this is an Alibaba Cloud ECS error

{
	"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"
}

This is the Sina API

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

or so

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

How can we further improve,

The next article will continue to share, leave your thoughts

Prepare to make a set of your own development scaffolding templates from scratch, and pay attention to public programmers for three hours

Guess you like

Origin blog.csdn.net/u011738045/article/details/130475379