1、自定义异常如何定义
package com.itheima.reggie.common;
/**
* @ClassName CustomException
* @Description 自定义异常
* @Author LPS
* @Date 2023/8/13 21:52
*/
public class CustomException extends RuntimeException{
private String msg;
public CustomException(String msg) {
super(msg);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2、系统异常和自定义异常如何统一处理 (全局异常处理)
package com.itheima.reggie.handler;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @ClassName GlobExceptionHandler
* @Description 全局异常处理器
* @Author LPS
* @Date 2023/8/13 21:57
*/
@RestControllerAdvice // 通知
public class GlobExceptionHandler {
/**
* 自定义异常的处理 通知
*
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
private ResultInfo handlerCustomException(CustomException e) {
return ResultInfo.error(e.getMsg()); // ResultInfo 统一结果的返回
}
/**
* 系统异常的处理
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
private ResultInfo handlerSystemException(Exception e) {
e.printStackTrace();
return ResultInfo.error("系统出错了,请联系管理员");
}
/**
* 应对mysql字段重复
* @param d
* @return
*/
@ExceptionHandler(DuplicateKeyException.class)
private ResultInfo handlerDuplicateKeyException(DuplicateKeyException d){
d.printStackTrace();
return ResultInfo.error("您输入的内容存在...");
}
}
如果往mysql数据库中存入数据,但是某一字段可能因为设置了唯一约束,导致字段重复会报一下错误: