当前位置: 首页 > article >正文

SpringMVC 1.请求参数检查 2.全局异常处理 3.请求参数封装为Pojo

ErrorEnum.java // 枚举所有的错误

package com.example.demo.enums;

import lombok.Getter;

public enum ErrorEnum {
    SYSTEM_ERROR(-1, "系统错误"),
    PARAM_ERROR(-2, "参数错误"),
    OK(0, "成功"),
    ;

    @Getter
    private final int code;
    @Getter
    private final String errorMsg;

    ErrorEnum(int code, String errorMsg) {
        this.code = code;
        this.errorMsg = errorMsg;
    }
}

LogicException.java // 逻辑异常封装

package com.example.demo.core;

import com.example.demo.enums.ErrorEnum;
import lombok.Getter;

public class LogicException extends RuntimeException {
    @Getter
    private final ErrorEnum errorEnum;

    public LogicException(ErrorEnum errorEnum) {
        super(String.format("errorCode=%d,errorMsg=%s", errorEnum.getCode(), errorEnum.getErrorMsg()));
        this.errorEnum = errorEnum;
    }
}

ResponseEntity.java // 返回值封装

package com.example.demo.core;

import com.example.demo.enums.ErrorEnum;
import lombok.AllArgsConstructor;
import lombok.Data;

@AllArgsConstructor
@Data  // 注意这个!!!
public class ResponseEntity<T> {
    private final int code;
    private final T data;
    private final String errorMsg;

    public static <T> ResponseEntity<T> success(T data) {
        return new ResponseEntity<>(ErrorEnum.OK.getCode(), data, ErrorEnum.OK.getErrorMsg());
    }

    public static ResponseEntity<Void> exception(ErrorEnum errorEnum) {
        return new ResponseEntity<>(errorEnum.getCode(), null, errorEnum.getErrorMsg());
    }
}

IReuqest.java // 用于检查接口

package com.example.demo.core;

public interface IRequest {
    /**
     * 进行参数错误检检查
     */
    void checkParamError();
}

GlobalExceptionCatch.java // 全局异常捕获

package com.example.demo.core;

import com.example.demo.enums.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionCatch {

    @ExceptionHandler(Throwable.class)
    public ResponseEntity<Void> exceptionHandler(Throwable e) {
        log.error("globalException=", e);

        // 默认是系统错误
        ErrorEnum errorEnum = ErrorEnum.SYSTEM_ERROR;

        // 逻辑错误
        if (e instanceof LogicException) {
            LogicException logicException = (LogicException) e;
            errorEnum = logicException.getErrorEnum();
        }

        return ResponseEntity.exception(errorEnum);
    }
}

AccountController.java

package com.example.demo.controller;

import com.example.demo.core.LogicException;
import com.example.demo.core.ResponseEntity;
import com.example.demo.msg.RegisterRequest;
import com.example.demo.msg.RegisterResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/account")
public class AccountController {
    /**
     * 情况1:
     * http://localhost:8080/account/register?username="xx"&password="123"
     * 返回:
     * {"code":0,"data":{"username":"a1","password":"1231"},"errorMsg":"成功"}
     * 情况2:
     * http://localhost:8080/account/register
     * 返回:{"code":-2,"data":null,"errorMsg":"参数错误"}
     * 同时打印了错误
     *
     * @param request
     * @return
     */
    @RequestMapping("/register")
    public ResponseEntity<RegisterResponse> register(RegisterRequest request) throws LogicException {
        request.checkParamError();

        // 返回
        RegisterResponse response = new RegisterResponse();
        response.setUsername(request.getUsername());
        response.setPassword(request.getPassword());

        return ResponseEntity.success(response);
    }
}

RegisterRequest.java

package com.example.demo.msg;

import com.example.demo.core.IRequest;
import com.example.demo.enums.ErrorEnum;
import com.example.demo.core.LogicException;
import lombok.Data;
import org.springframework.util.StringUtils;

@Data
public class RegisterRequest implements IRequest {
    private String username;
    private String password;

    @Override
    public void checkParamError() {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new LogicException(ErrorEnum.PARAM_ERROR);
        }
    }
}

RegisterResponse.java

package com.example.demo.msg;

import lombok.Data;

@Data
public class RegisterResponse {
    private String username;
    private String password;
}


http://www.kler.cn/a/231947.html

相关文章:

  • [前端面试]javascript
  • 3D意识(3D Awareness)浅析
  • 跟我学C++中级篇——RAII
  • Javascript_设计模式(二)
  • [Codesys]常用功能块应用分享-BMOV功能块功能介绍及其使用实例说明
  • 深度神经网络DNN反向传播BP算法公式推导
  • 了解海外云手机的多种功能
  • 学习 Redis 基础数据结构,不讲虚的。
  • Docker容器监控-CIG
  • 机器学习 | 深入集成学习的精髓及实战技巧挑战
  • Compose | UI组件(十五) | Scaffold - 脚手架
  • C++基础知识点预览
  • MVC框架学习
  • springboot项目启动报错:dynamic-datasource can not find primary datasource
  • 《Git 简易速速上手小册》第7章:处理大型项目(2024 最新版)
  • 黑豹程序员-ElementPlus选择图标器
  • 04 使用gRPC实现客户端和服务端通信
  • Go语言Gin框架安全加固:全面解析SQL注入、XSS与CSRF的解决方案
  • 倒计时61天
  • 实景三维数据库管理系统助力实景三维中国建设
  • 【C++修行之道】(引用、函数提高)
  • CMake编译JSONCPP库
  • JCIM | MD揭示PTP1B磷酸酶激活RtcB连接酶的机制
  • 视频上传 - 断点续传那点事
  • 相机图像质量研究(3)图像质量测试介绍
  • L1-088 静静的推荐