Java异常处理-前端参数优雅返回异常结果

2024-06-20 06:48

本文主要是介绍Java异常处理-前端参数优雅返回异常结果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

目录

1 引言

2 什么是异常

2.1 Java中的异常体系

3 常见的处理方式

3.1 参数传递结果

3.2 每个方法都返回结果对象,或者状态码

错误码

调用的方法都返回错误码

3.3 自定义异常并捕获处理

异常定义

异常处理

4 spring-boot中处理方式

4.1 controller

4.2 数据传输对象

4.3 自定义校验注解

4.4 解释注解

4.5 全局处理异常

5 效果

5.1 自定义参数异常

5.2 自定义校验注解异常



1 引言

异常处理是程序员开发的必修课。

2 什么是异常

程序运行中的非正常行为,例如给用户的录入不符合规范,或者由于疏忽有的对象没有赋值,或者使用数组时调用的下标超标等等都可以称为程序的异常。异常都会造成程序出错中断,是很严重的行为,所以我们要处理可能出现的各种异常。

2.1 Java中的异常体系

待补充理论知识

3 常见的处理方式

处理异常的方式很多。

3.1 参数传递结果

以下代码模拟登录操作,传入的用户名和密码,先后经过用户名校验、密码校验、查询数据库,并返回结果。这里使用Response透传整个处理流程。

package com.param.validate.main;import com.alibaba.fastjson.JSON;
import com.param.validate.common.constant.UserConstant;
import com.param.validate.common.enums.ResponseCode;
import com.param.validate.dto.UserDTO;
import com.param.validate.vo.Response;
import com.param.validate.vo.UserVO;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
public class LoginMain {/*** 登录过程* @param userDTO 用户数据传输对象* @return*/public Response<UserVO> login(UserDTO userDTO){// 事先声明一个最终对象,该对象会伴随后续处理Response<UserVO> response = new Response<>();checkUsername(userDTO.getUsername(),response);if(response.getCode()!=null){return response;}checkPassword(userDTO.getUsername(),response);if(response.getCode()!=null){return response;}UserVO userVO = mockQueryUserInfo(userDTO.getUsername(), userDTO.getPassword());response.setCode(ResponseCode.OK.getCode());response.setMessage(ResponseCode.OK.getMessage());response.setResult(userVO);return response;}/*** 校验用户名* @param username 用户名* @param response 返回结果*/public void checkUsername(String username, Response<UserVO> response){// 不能为空if(null==username||username.length()==0){response.setCode(ResponseCode.USERNAME_EMPTY.getCode());response.setMessage(ResponseCode.USERNAME_EMPTY.getMessage());return;}// 长度不能超过32位if(username.length()> UserConstant.USERNAME_LIMIT){response.setCode(ResponseCode.USERNAME_INVALID.getCode());response.setMessage(ResponseCode.USERNAME_INVALID.getMessage());}}/*** 校验密码* @param password 密码* @param response 返回结果*/public void checkPassword(String password,Response<UserVO> response){// 不能为空if(null==password||password.length()==0){response.setCode(ResponseCode.PASSWORD_EMPTY.getCode());response.setMessage(ResponseCode.PASSWORD_EMPTY.getMessage());return;}// 长度不能超过16位if(password.length()> UserConstant.PASSWORD_LIMIT){response.setCode(ResponseCode.PASSWORD_INVALID.getCode());response.setMessage(ResponseCode.PASSWORD_INVALID.getMessage());}}/***  模拟登录* @param username 用户名* @param password 密码* @return*/public UserVO mockQueryUserInfo(String username, String password) {return UserVO.builder().username(username).password(password).age(18).sex("男").build();}public static void main(String[] args) {UserDTO userDTO = new UserDTO("","123456");LoginMain loginMain = new LoginMain();Response<UserVO> login = loginMain.login(userDTO);System.out.println(JSON.toJSONString(login));}
}

3.2 每个方法都返回结果对象,或者状态码

错误码

package com.param.validate.common.enums;import com.param.validate.vo.Response;
import lombok.Getter;
import org.springframework.http.HttpStatus;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
@Getter
public enum ResponseCode {/*** 0,代表成功*/OK(HttpStatus.OK, 0, "成功"),/*** [-100000~0),参数错误*/USERNAME_EMPTY(HttpStatus.BAD_REQUEST, -100001, "用户名为空"),USERNAME_INVALID(HttpStatus.BAD_REQUEST, -100002, "用户名无效"),PASSWORD_EMPTY(HttpStatus.BAD_REQUEST, -100003, "密码为空"),PASSWORD_INVALID(HttpStatus.BAD_REQUEST, -100004, "密码无效"),PARAM_ERROR(HttpStatus.BAD_REQUEST,-100005,"参数错误"),/*** [-200000,-100000),服务端内部错误*/QUERY_USERNAME_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, -200001, "查询用户名异常"),UNKOWN(HttpStatus.INTERNAL_SERVER_ERROR, -200002, "未知错误");private HttpStatus httpStatus;private Integer code;private String message;ResponseCode(HttpStatus httpStatus, Integer code, String message) {this.httpStatus = httpStatus;this.code = code;this.message = message;}
}

调用的方法都返回错误码

package com.param.validate.main;import com.alibaba.fastjson.JSON;
import com.param.validate.common.constant.UserConstant;
import com.param.validate.common.enums.ResponseCode;
import com.param.validate.dto.UserDTO;
import com.param.validate.vo.Response;
import com.param.validate.vo.UserVO;
import org.apache.catalina.User;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
public class LoginOtherMain {/*** 登录过程* @param userDTO 用户数据传输对象* @return*/public Response<UserVO> login(UserDTO userDTO){ResponseCode responseCode = checkUsername(userDTO.getUsername());if(responseCode!=null){return Response.error(responseCode);}ResponseCode code = checkPassword(userDTO.getUsername());if(code!=null){return Response.error(code);}Response<UserVO> response = new Response<UserVO>();UserVO userVO = mockQueryUserInfo(userDTO.getUsername(), userDTO.getPassword());response.setCode(ResponseCode.OK.getCode());response.setMessage(ResponseCode.OK.getMessage());response.setResult(userVO);return response;}/*** 校验用户名* @param username 用户名*/public ResponseCode checkUsername(String username){// 不能为空if(null==username||username.length()==0){return ResponseCode.USERNAME_EMPTY;}// 长度不能超过32位if(username.length()> UserConstant.USERNAME_LIMIT){return ResponseCode.USERNAME_INVALID;}return null;}/*** 校验密码* @param password 密码*/public ResponseCode checkPassword(String password){// 不能为空if(null==password||password.length()==0){return ResponseCode.PASSWORD_EMPTY;}// 长度不能超过16位if(password.length()> UserConstant.PASSWORD_LIMIT){return ResponseCode.PASSWORD_INVALID;}return null;}/***  模拟登录* @param username 用户名* @param password 密码* @return*/public UserVO mockQueryUserInfo(String username, String password) {return UserVO.builder().username(username).password(password).age(18).sex("男").build();}public static void main(String[] args) {UserDTO userDTO = new UserDTO("","123456");LoginOtherMain loginOtherMain = new LoginOtherMain();Response<UserVO> login = loginOtherMain.login(userDTO);System.out.println(JSON.toJSONString(login));}}

3.3 自定义异常并捕获处理

自定义异常并捕获处理。

异常定义

package com.param.validate.common.exception;import com.param.validate.common.enums.ResponseCode;
import lombok.Getter;
import lombok.Setter;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
@Setter
@Getter
public class LoginExcetion extends RuntimeException{private ResponseCode code;public LoginExcetion (ResponseCode code) {super(code.getMessage());this.code = code;}/*** 不写入堆栈信息,提高性能*/@Overridepublic Throwable fillInStackTrace() {return this;}}

异常处理

package com.param.validate.main;import com.alibaba.fastjson.JSON;
import com.param.validate.common.constant.UserConstant;
import com.param.validate.common.enums.ResponseCode;
import com.param.validate.common.exception.LoginExcetion;
import com.param.validate.dto.UserDTO;
import com.param.validate.vo.Response;
import com.param.validate.vo.UserVO;
import org.apache.catalina.User;
import org.apache.logging.log4j.LoggingException;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
public class LoginOtherMain {/*** 登录过程** @param userDTO 用户数据传输对象* @return*/public Response<UserVO> login(UserDTO userDTO) {checkUsername(userDTO.getUsername());checkPassword(userDTO.getUsername());UserVO userVO = mockQueryUserInfo(userDTO.getUsername(), userDTO.getPassword());Response<UserVO> response = new Response<UserVO>();response.setCode(ResponseCode.OK.getCode());response.setMessage(ResponseCode.OK.getMessage());response.setResult(userVO);return response;}/*** 校验用户名** @param username 用户名*/public void checkUsername(String username) {// 不能为空if (null == username || username.length() == 0) {throw new LoginExcetion(ResponseCode.USERNAME_EMPTY);}// 长度不能超过32位if (username.length() > UserConstant.USERNAME_LIMIT) {throw new LoginExcetion(ResponseCode.USERNAME_INVALID);}}/*** 校验密码** @param password 密码*/public void checkPassword(String password) {// 不能为空if (null == password || password.length() == 0) {throw new LoginExcetion(ResponseCode.PASSWORD_EMPTY);}// 长度不能超过16位if (password.length() > UserConstant.PASSWORD_LIMIT) {throw new LoginExcetion(ResponseCode.PASSWORD_INVALID);}}/*** 模拟登录** @param username 用户名* @param password 密码* @return*/public UserVO mockQueryUserInfo(String username, String password) {return UserVO.builder().username(username).password(password).age(18).sex("男").build();}public static void main(String[] args) {UserDTO userDTO = new UserDTO("", "123456");LoginOtherMain loginOtherMain = new LoginOtherMain();Response<UserVO> login = null;try {login = loginOtherMain.login(userDTO);} catch (LoginExcetion e) {login = Response.error(e.getCode());} catch (Exception e) {login =Response.error(ResponseCode.UNKOWN);}System.out.println(JSON.toJSONString(login));}}

4 spring-boot中处理方式

4.1 controller

controller会校验post参数和get参数。

package com.param.validate.controller;import javax.validation.Valid;
import javax.validation.constraints.Size;import com.param.validate.dto.UserDTO;
import com.param.validate.service.LoginService;
import com.param.validate.validator.annotation.ValidPassword;
import com.param.validate.vo.Response;
import com.param.validate.vo.UserVO;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/@Slf4j
@RequestMapping("/v1/user/login")
@RestController
// get校验时需要这个
@Validated
public class LoginController {@Autowiredprivate LoginService loginService;@PostMappingpublic ResponseEntity<Response<UserVO>> login(@Valid @RequestBody UserDTO userDTO){UserVO user = loginService.findUser(userDTO.getUsername(), userDTO.getPassword());return ResponseEntity.ok(Response.ok(user));}@GetMapping("/{password}")public ResponseEntity<Response<UserVO>> getUserVO(@PathVariable("password")@Size(min = 8,max = 32,message = "密码区间限制")String password){UserVO userVO = UserVO.builder().username("zhangsansssssss").password(password).build();return ResponseEntity.ok(Response.ok(userVO));}}

4.2 数据传输对象

传入的登录对象,使用自定义注解校验参数

package com.param.validate.dto;import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;import com.param.validate.validator.annotation.ValidPassword;
import lombok.Getter;
import lombok.Setter;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/29*/
@Setter
@Getter
public class UserDTO {@NotEmpty(message = "Username is empty.")@Size(min = 8,max = 32,message = "Username length invalid.")private String username;@NotEmpty(message = "Password is empty.")@Size(min = 8,max = 32,message = "Password length invalid.")@ValidPasswordprivate String password;public UserDTO(String username, String password) {this.username = username;this.password = password;}public UserDTO(){}
}

4.3 自定义校验注解

/** Copyright (c) 2021, TP-Link Corporation Limited. All rights reserved.*/package com.param.validate.validator.annotation;import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;import com.param.validate.validator.PasswordValidator;import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;/*** Description** @author qiu* @version 1.0*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = PasswordValidator.class)
public @interface ValidPassword {String message() default "密码只能是数字";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}

4.4 解释注解

/** Copyright (c) 2021, TP-Link Corporation Limited. All rights reserved.*/
package com.param.validate.validator;import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;import com.param.validate.validator.annotation.ValidPassword;
import lombok.extern.slf4j.Slf4j;/*** Description** @author qiu* @version 1.0*/
@Slf4j
public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {@Overridepublic void initialize(ValidPassword constraintAnnotation) {}@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {if (value == null) {return true;}boolean matches = value.matches("[0-9]+");if(matches){return true;}return false;}
}

4.5 全局处理异常

package com.param.validate.handler;import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;import com.param.validate.common.enums.ResponseCode;
import com.param.validate.common.exception.LoginExcetion;
import com.param.validate.common.exception.QueryException;
import com.param.validate.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;/*** Description of this file** @author qiu* @version 1.0* @since 2021/12/30*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/*** 处理get方法的参数异常情况* @param request 请求体,如果需要获取请求体的信息时,可以用到* @param ex 抛出的异常* @return*/@ExceptionHandler(ConstraintViolationException.class)@ResponseBodypublic ResponseEntity handlerConstraintViolationException(HttpServletRequest request,ConstraintViolationException ex) {Set<ConstraintViolation<?>> errors = ex.getConstraintViolations();StringBuilder messageBuilder = new StringBuilder();errors.forEach(constraintViolation -> messageBuilder.append(constraintViolation.getMessage()));return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.error(ResponseCode.PARAM_ERROR.getCode(), messageBuilder.toString()));}/*** 使用@RequestBody @Valid 对JSON参数进行获取和校验,抛出异常会走该路径* @param request 请求体,如果要用到的话* @param ex 抛出的异常* @return*/@ExceptionHandler(value = MethodArgumentNotValidException.class)@ResponseBodypublic ResponseEntity handlerBeanValidationException(HttpServletRequest request,MethodArgumentNotValidException ex) {System.out.println("222");List<ObjectError> errors = ex.getBindingResult().getAllErrors();StringBuilder messageBuilder = new StringBuilder();errors.forEach(error -> messageBuilder.append(error.getDefaultMessage()).append(";"));return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.error(ResponseCode.PARAM_ERROR.getCode(), messageBuilder.toString()));}/**** @param e 抛出的自定义异常* @return*/@ExceptionHandler(LoginExcetion.class)public ResponseEntity handleLoginExcetion(LoginExcetion e) {ResponseCode code = e.getCode();return ResponseEntity.status(code.getHttpStatus()).body(Response.error(code));}/**** @param e 抛出的自定义异常* @return*/@ExceptionHandler(QueryException.class)public ResponseEntity handleCombinedException(QueryException e) {ResponseCode code = e.getCode();return ResponseEntity.status(code.getHttpStatus()).body(Response.error(code));}/**** @param e 程序没有处理的未知异常* @return*/@ExceptionHandler(Exception.class)public ResponseEntity handleException(Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Response.error(ResponseCode.UNKOWN));}
}

5 效果

5.1 自定义参数异常

5.2 自定义校验注解异常

5.3 get方法校验

 

这篇关于Java异常处理-前端参数优雅返回异常结果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1077398

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

vue, 左右布局宽,可拖动改变

1:建立一个draggableMixin.js  混入的方式使用 2:代码如下draggableMixin.js  export default {data() {return {leftWidth: 330,isDragging: false,startX: 0,startWidth: 0,};},methods: {startDragging(e) {this.isDragging = tr