自定义异常类
import lombok.Data;
@Data
public class BusinessException extends RuntimeException{
private Integer code;
public BusinessException(String message) {
super(message);
this.code = 500;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
统一异常处理
import com.example.mybatisplusdemo.util.ResultUtil;
import com.example.mybatisplusdemo.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(BusinessException.class)
public Result handle(BusinessException e){
return ResultUtil.fail(e.getCode(),e.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Result handle(Exception e){
return ResultUtil.fail(500,e.getMessage());
}
}
- 会优先匹配自己的异常,如果匹配不到,就走exception
- 与
handle
写的顺序无关