1.自定义异常类 继承RuntimeException
public class CustomException extends RuntimeException {
private final String msg;
public CustomException(String message) {
super(message);
this.msg = message;
}
public String getMessage() {
return msg;
}
}
2.创建一个全局异常处理类GlobalExceptionHandler,在里面处理我们抛出的异常处理。(可自定义异常处理)
import com.ropz.demo.config.ResponseResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice//这个注解标记的类都表示全局异常处理类,并返回json数据格式
public class GlobalExceptionHandler {
@ExceptionHandler(value = CustomException.class)
public ResponseResult businessException(CustomException customException){
return ResponseResult.error(customException.getMessage(),500,null);
}
}
3.自定义封装的结果集ResponseResult类
import lombok.Data;
@Data
public class ResponseResult{
private String msg;
private int code;
private Object data;
public ResponseResult(String msg, int code, Object data){
this.msg = msg;
this.code = code;
this.data = data;
}
public static ResponseResult success(String msg, int code, Object data) {
return new ResponseResult(msg, code, data);
}
public static ResponseResult error(String msg, int code, Object data) {
return new ResponseResult(msg, code, data);
}
}
SpringBoot中的自定义异常处理与JSON响应
972

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



