自定义异常类
import com.atguigu.common.result.ResultCodeEnum;
import lombok.Data;
@Data
public class MyExceptionextends extend RuntimeException {
private Integer code;
private String message;
public MyException(Integer code, String message) {
super(message);
this.code = code;
this.message = message;
}
public MyException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
this.message = resultCodeEnum.getMessage();
}
@Override
public String toString() {
return "GuliException{" +
"code=" + code +
", message=" + this.getMessage() +
'}';
}
}
全局异常处理
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.ResponseStatus;
import org.springframework.http.HttpStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail().message("执行全局异常处理");
}
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.fail().message("执行特定异常处理");
}
@ExceptionHandler(MyException.class)
@ResponseBody
public Result error(MyException e){
e.printStackTrace();
return Result.fail().message("执行自定义异常处理");
}
@ExceptionHandler({ MissingServletRequestParameterException.class, HttpMessageNotReadableException.class,
UnsatisfiedServletRequestParameterException.class, MethodArgumentTypeMismatchException.class })
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo badRequestException(Exception e) {
e.printStackTrace();
HttpStatus.BAD_REQUEST.value();
return Result.fail().message(e.getMessage());
}
}