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;
}
相关推荐
猫头虎6 小时前
[特殊字符]解决 “IDEA 登录失败。不支持早于 14.0 的 GitLab 版本” 问题的几种方法
java·ide·网络协议·http·https·gitlab·intellij-idea
扣丁梦想家7 小时前
✅ 常用 Java HTTP 客户端汇总及使用示例
java·开发语言·http
2501_916007479 小时前
绕过 Xcode?使用 Appuploader和主流工具实现 iOS 上架自动化
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_916013749 小时前
使用 Windows 完成 iOS 应用上架:Appuploader对比其他证书与上传方案
websocket·网络协议·tcp/ip·http·网络安全·https·udp
济宁雪人10 小时前
HTTP协议
网络·网络协议·http
emo了小猫11 小时前
HTTP连接管理——短连接,长连接,HTTP 流水线
网络·网络协议·http
余辉zmh11 小时前
【Linux网络篇】:从HTTP到HTTPS协议---加密原理升级与安全机制的全面解析
linux·网络·http
muyouking1111 小时前
用 n8n 提取静态网页内容:从 HTTP Request 到 HTML 节点全解析
网络协议·http·html
昔我往昔1 天前
https和http有什么区别-http各个版本有什么区别
网络协议·http·https
alien爱吃蛋挞1 天前
【JavaEE】万字详解HTTP协议
网络·网络协议·http