SprinBoot自定义异常(统一异常处理)
统一返回类Result
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private String code;
private String msg;
private Object data;
public static Result success(){
return new Result(Constants.CODE_200,"",null);
}
public static Result success(Object data){
return new Result(Constants.CODE_200,"",data);
}
public static Result error(String code,String msg){
return new Result(code,msg,null);
}
public static Result error(){
return new Result(Constants.CODE_500,"系统错误",null);
}
}
public interface Constants {
String CODE_200="200"; //成功
String CODE_500="500"; //系统错误
String CODE_401="401"; //权限不足
String CODE_400="400"; //参数错误
String CODE_600="600"; //其他业务异常
}
自定义异常类
import com.tian.springboot.controller.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(ServiceException.class)
@ResponseBody
public Result hanle(ServiceException se){
return Result.error(se.getCode(),se.getMessage());
}
}
import lombok.Getter;
@Getter
public class ServiceException extends RuntimeException{
private String code;
public ServiceException(String code,String msg){
super(msg);
this.code=code;
}
}
使用
private User getUserInfo(UserDTO userDTO){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username",userDTO.getUsername());
wrapper.eq("password",userDTO.getPassword());
User one;
try {
one = getOne(wrapper);
}catch (Exception e){
LOG.error(e);
throw new ServiceException(Constants.CODE_500,"系统错误");
// throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
}
return one;
}
然后控制台如果报错就会显示你自定义的信息
SpringBoot自定义异常处理与统一封装
本文介绍了如何在SpringBoot应用中实现自定义异常处理,包括创建统一的响应类Result,定义常量枚举Constants,自定义异常ServiceException,以及全局异常处理器GlobalExceptionHandle。通过这种方式,可以统一返回错误信息,提高代码的可维护性和用户体验。
1335

被折叠的 条评论
为什么被折叠?



