SpringBoot:返回结果封装及自定义异常处理
在web中,结果往往被封装,返回为Json格式,也便于数据交换。
在web中,我们需要自定义一些异常,以便对一些异常进行特定处理。
返回结果封装
- 结果常被封装为一个统一格式的结果类,由三部分组成:消息、状态码、数据(泛型)
- 统一格式如下,基本大同小异
public class ResultUtil<E> implements Serializable {
private int StatuCode;
private String message;
private E data;
public ResultUtil(int statuCode, String message, E data) {
StatuCode = statuCode;
this.message = message;
this.data = data;
}
public int getStatuCode() {
return StatuCode;
}
public void setStatuCode(int statuCode) {
StatuCode = statuCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}
自定义异常处理
- 异常相关知识:java异常均来自超级父类Throwable,Throwable有两个异常子类,其中一个为Exception,运行时出现,另一个为错误,错误往往会在编译阶段出现。Exception有子类RuntimeException。
- 我们自定义异常基类往往继承自RuntimeException(IDEA重构父类方法快捷键ctrl+O),其他自定义异常再继承自异常基类,示例如下:
public class RuntimeException extends Exception {
static final long serialVersionUID = -7034897190745766939L;
public RuntimeException() {
super();
}
public RuntimeException(String message) {
super(message);
}
public RuntimeException(String message, Throwable cause) {
super(message, cause);
}
public RuntimeException(Throwable cause) {
super(cause);
}
protected RuntimeException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public class FindNullException extends BaseException{
public FindNullException() {
super();
}
public FindNullException(String message) {
super(message);
}
public FindNullException(String message, Throwable cause) {
super(message, cause);
}
public FindNullException(Throwable cause) {
super(cause);
}
protected FindNullException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}