编辑
2025-08-09
java web
00
请注意,本文编写于 118 天前,最后修改于 118 天前,其中某些信息可能已经过时。

目录

1、枚举一些通用异常
2、继承RuntimeException自定义异常
3、约定响应统一类型
4、全局异常处理器

定义全局异常处理可以避免前端发送的请求因未提供异常处理而返回服务端报错信息,并规范项目结构,也确保项目有良好的可扩展性。

异常处理流程:

全局异常处理可如下进行:

1、枚举一些通用异常

public enum CommonError { UNKOWN_ERROR("执行过程异常,请重试。"), PARAMS_ERROR("非法参数"), OBJECT_NULL("对象为空"), QUERY_NULL("查询结果为空"), REQUEST_NULL("请求参数为空"); private String errMessage; public String getErrMessage() { return errMessage; } private CommonError( String errMessage) { this.errMessage = errMessage; } }

2、继承RuntimeException自定义异常

public class GlobalException extends RuntimeException{ private String errMessage; public GlobalException() { } public GlobalException(String message) { super(message); this.errMessage = message; } public String getErrMessage() { return errMessage; } public void setErrMessage(String errMessage) { this.errMessage = errMessage; } public static void cast(String message){ throw new GlobalException(message); } public static void cast(CommonError commonError){ throw new GlobalException(commonError.getErrMessage()); } }

3、约定响应统一类型

public class GlobalExceptionResponse implements Serializable { private String errMessage; public GlobalExceptionResponse(String errMessage) { this.errMessage = errMessage; } public String getErrMessage() { return errMessage; } public void setErrMessage(String errMessage) { this.errMessage = errMessage; } }

4、全局异常处理器

Spring3.0以上版本提供了@ControllerAdvice、@ResponseStatus、@ExceptionHandler注解解决Spring MVC中出现的异常信息

@ControllerAdvice:处理多个controller的异常

@ExceptionHandler:处理多个方法的异常

@ResponseStatus:指定方法抛出异常时的状态码

@Slf4j @ControllerAdvice public class GlobalExcepHandler { //自定义异常处理 @ResponseBody @ExceptionHandler(GlobalException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public RestErrorResponse customException(GlobalException e){ //记录异常 log.error("系统异常{}", e.getErrMessage(), e); //解析异常 String errMessage = e.getErrMessage(); return new RestErrorResponse(errMessage); } //系统异常处理 @ResponseBody @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public RestErrorResponse exception(Exception e){ log.error("系统异常{}", e.getMessage(), e); return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage()); } }

本文作者:寒江孤影

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!