日常开发中,我们一般都是自定义统一的异常类
自定义异常可以携带更多的信息。
项目开发中经常是很多人负责不同的模块,使用自定义异常可以统一了对外异常展示的方式。
自定义异常语义更加清晰明了,一看就知道是项目中手动抛出的异常。
自定义异常类, 所在包结构:
/**
* 基础异常
* @author spikeCong
* @date 2023/2/28
**/
public class BaseException extends RuntimeException{
/**
* 错误码
*/
private String code;
/**
* 错误消息
*/
private String defaultMessage;
public BaseException() {
}
public BaseException(String code, String defaultMessage) {
this.code = code;
this.defaultMessage = defaultMessage;
}
public String getCode() {
return code;
}
public String getDefaultMessage() {
return defaultMessage;
}
}
在controller 层,我们来使用这个自定义异常:
@RequestMapping("/queryUser")
public BaseResponse queryUser(User user){
//模拟查询失败抛出异常
throw new BaseException("500","测试异常类!");
}
这时我们可以借助注解@RestControllerAdvice,让代码更优雅。@RestControllerAdvice是一个应用于Controller层的切面注解,它一般配合@ExceptionHandler注解一起使用,作为项目的全局异常处理。示例代码如下:
/**
* 全局异常处理器
* @author spikeCong
* @date 2023/2/28
**/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BaseException.class)
@ResponseBody
public BaseResponse baseExceptionHandler(BaseException e){
return BaseResponse.fail(e.getDefaultMessage());
}
}
我们有想要拦截的异常类型,比如想拦截BaseException类型,就新增一个方法,使用@ExceptionHandler注解修饰,并指定你想处理的异常类型,接着在方法内编写对该异常的操作逻辑,就完成了对该异常的全局处理!
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 基础异常
* @param e
* @return: com.msb.hjycommunity.common.core.domain.BaseResponse
*/
@ExceptionHandler(BaseException.class)
@ResponseBody
public BaseResponse baseExceptionHandler(BaseException e){
return BaseResponse.fail(e.getDefaultMessage());
}
}
测试
http://localhost:8888/hejiayun/user/queryUser
{
"code": "500",
"message": "测试异常类!",
"data": null
}