Spring Boot异常处理 - Json格式

Spring Boot应用异常统一返回Json格式的数据。

ExceptionControl.java

@Controller
public class ExceptionControl implements ErrorController {

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping(value = {"/error"})
  @ResponseBody
  public ResObject error() {
		return ResObject.res(404,"not found");
	}
}

ExceptionAdvice.java

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionAdvice {
		 
  @ExceptionHandler(value = {Exception.class})
  @ResponseBody
  public Object error(Exception ex){
  	ex.printStackTrace();
  	return ResObject.res(500,"error");
  }

}

ResObject.java

注:此类根据实际情况取舍。

public class ResObject {

	private Integer code = 200;

	private String msg;

	public Object data;
	
	public static ResObject res(Integer code, String msg) {
		ResObject resBean = new ResObject(code);
		resBean.msg = msg;
		return resBean;
	}

	public static ResObject ok() {
		ResObject resBean = new ResObject();
		resBean.msg = "操作成功";
		resBean.code = 200;
		return resBean;
	}

	public static ResObject fail() {
		ResObject resBean = new ResObject();
		resBean.msg = "操作失败";
		resBean.code = 300;
		return resBean;
	}
.......
}