springboot快速入门-5.添加返回值和异常处理


添加统一返回类型

在base中新建包vo,并新建java类:Result.java

package com.example.demo.base.vo;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.Serializable;

/**
 * 接口返回数据格式
 * @author DaenMax
 * @param 
 */
@Data
public class Result implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 返回代码
     */
    private Integer code = 0;

    /**
     * 成功标志
     */
    private boolean success = true;

    /**
     * 返回处理消息
     */
    private String msg = "操作成功";

    /**
     * 返回数据对象 data
     */
    private T result;

    /**
     * 时间戳
     */
    private long timestamp = System.currentTimeMillis();

    public Result() {
    }

    /**
     * success
     */
    public Result success() {
        this.code = 200;
        return this;
    }
    public Result success(String msg) {
        this.msg = msg;
        this.code = 200;
        return this;
    }

    /**
     * ok
     */
    public static Result ok() {
        Result r = new Result<>();
        r.setCode(200);
        r.setSuccess(true);
        return r;
    }

    public static Result ok(String msg) {
        Result r = new Result<>();
        r.setCode(200);
        r.setSuccess(true);
        r.setMsg(msg);
        return r;
    }

    public static Result ok(Object data) {
        Result r = new Result<>();
        r.setCode(200);
        r.setSuccess(true);
        r.setResult(data);
        return r;
    }

    public static Result ok(Object data, String msg) {
        Result r = new Result<>();
        r.setCode(200);
        r.setSuccess(true);
        r.setResult(data);
        r.setMsg(msg);
        return r;
    }

    public static Result ok(String msg,Object data) {
        Result r = new Result<>();
        r.setSuccess(true);
        r.setCode(200);
        r.setMsg(msg);
        r.setResult(data);
        return r;
    }

    /**
     * error500
     */
    public Result error500() {
        this.code = 500;
        this.msg = "操作失败";
        this.success = false;
        return this;
    }
    public Result error500(String msg) {
        this.msg = msg;
        this.code = 500;
        this.success = false;
        return this;
    }

    public Result error420(String msg) {
        this.msg = msg;
        this.code = 420;
        this.success = false;
        return this;
    }

    /**
     * error
     */
    public static Result error(String msg) {
        return error(500, msg);
    }

    public static Result error(int code, String msg) {
        Result r = new Result<>();
        r.setCode(code);
        r.setMsg(msg);
        r.setSuccess(false);
        return r;
    }

    /**
     * 无权限,包含令牌不存在和令牌过期的情况
     */
    public static Result noAuth(String msg) {
        return error(510, msg);
    }

    /**
     * 手动转到JSON字符串
     * @return
     */
    public String toJsonString(){
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.put("code",this.code);
        jsonObject.put("success",this.success);
        jsonObject.put("msg",this.msg);
        jsonObject.put("result",this.result);
        jsonObject.put("timestamp",this.timestamp);
        return jsonObject.toJSONString();
    }

}


使用

return Result.ok("成功");

前端返回

{
    "code": 200,
    "success": true,
    "msg": "成功",
    "timestamp": 1640252605302
}

添加统一异常处理

在base中新建包exception,并新建java类:MyException.java

package com.example.demo.base.exception;

/**
 * 自定义异常处理
 * @author DaenMax
 */
public class MyException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public MyException(String message) {
        super(message);
    }
}

再新建java类:MyExceptionHandle.java

package com.example.demo.base.exception;

import com.example.demo.base.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 * @author DaenMax
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandle {

    /**
     * 处理自定义异常
     * @param e AbpException
     * @return Result
     */
    @ExceptionHandler(MyException.class)
    public Result<?> abpException(MyException e) {
        //log.error(e.getMessage(), e);
        log.info(e.getMessage());
        return Result.error(e.getMessage());
    }



    /**
     * NotBlank异常处理
     * @param e MethodArgumentNotValidException
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> argumentException(MethodArgumentNotValidException e){
        log.error(e.getMessage(), e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return Result.error("操作失败," + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 入参格式错误导致的序列化失败
     * @param e HttpMessageNotReadableException
     * @return Result
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<?> jsonParseException(HttpMessageNotReadableException e) {
        log.warn("参数格式错误", e);
        return Result.error("参数格式错误");
    }

    /**
     * 请求参数不全
     * @param e MissingServletRequestParameterException
     * @return Result
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<?> missingRequestParam(MissingServletRequestParameterException e) {
        log.warn("请求参数不全", e);
        return Result.error("参数不全,请检查后重试");
    }

    /**
     * 以上未处理的异常
     * @param e Exception
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e){
        log.error("未处理的异常信息:", e);
        return Result.error("操作失败,请联系管理员");
    }

}

测试异常处理

	@GetMapping("/test2")
    public Result test2(HttpServletRequest request){
        String a = null;
        try{
            String b = a.toString();
        } catch (NullPointerException e){
            throw new MyException("空指针异常啦");
        }
        return Result.ok("请求成功");
    }

前端返回

{"code":500,"success":false,"msg":"空指针异常啦","result":null,"timestamp":1641288252853}