![](https://img-blog.csdnimg.cn/img_convert/088cc028fb27743cea91c4cf48052805.png)
自定义业务异常
package com.example.exception;
/**
* 自定义业务异常类
*/
public class CustomException extends RuntimeException {
public CustomException(String message){
super(message);
}
}
全局异常处理
package com.example.exception;
import com.example.common.Constants;
import com.example.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* 全局异常处理
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法 sql异常
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
log.error(ex.getMessage());
if (ex.getMessage().contains("Duplicate entry")) {
String[] split = ex.getMessage().split(" ");
String msg = "用户" + split[2] + "已存在!";
return Result.error(Constants.CODE_400,msg);
}
return Result.error(Constants.CODE_500,"未知错误");
}
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(CustomException.class)
public Result exceptionHandler(CustomException ex){
log.error(ex.getMessage());
return Result.error(Constants.CODE_500,ex.getMessage());
}
}
springmvc的异常处理器
拦截所有异常信息
package com.example.exception;
import com.example.common.Constants;
import com.example.common.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//作为springmvc的异常处理器
//@ControllerAdvice
@RestControllerAdvice
public class ProjectExceptionAdvice {
//拦截所有的异常信息
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
//记录日志
//通知运维
//通知开发
ex.printStackTrace();
return Result.error(Constants.CODE_500,"服务器故障,请稍后再试!");
}
}