SpringBoot ErrorController 实践

SpringBoot的默认异常处理映射为“/error”。BasicErrorController已经默认实现了“text/html”的处理,如果想返回自定义JSON格式信息,则实现“ErrorController ”接口,增加一个produces 为“application/json”的方法即可,如:

@RestController
public class ExceptionController implements ErrorController {

    @Autowired
    private ErrorAttributes errorAttributes;

    /**
     * 默认错误
     */
    private static final String path_default = "/error";

    @Override
    public String getErrorPath() {
        return path_default;
    }

    /**
     * JSON格式错误信息
     */
    @RequestMapping(value = path_default,  produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseMessage error(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> body = this.errorAttributes.getErrorAttributes(requestAttributes, true);
        return ResponseMessage.fail("服务器端异常!", body);
    }

}

ResponseMessage 为自定义的实体类,用于向前端返回统一格式信息,结构如:

public class ResponseMessage {

    /**
     * 是否成功
     */
    private boolean success;

    /**
     * 返回文字
     */
    private String msg;

    /**
     * 返回数据
     */
    private Object data;

    public ResponseMessage() {
    }

    public ResponseMessage(boolean success, String msg, Object data) {
        this.success = success;
        this.msg = msg;
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static ResponseMessage success(){
        return new ResponseMessage(true, null, null);
    }

    /**
     * 成功返回方法
     * @param data 返回数据
     */
    public static ResponseMessage success(Object data){
        return new ResponseMessage(true, null, data);
    }

    /**
     * 失败返回方法--默认
     */
    public static ResponseMessage fail(){
        return new ResponseMessage(false, null, null);
    }

    /**
     * 失败返回方法
     * @param message 文字信息
     */
    public static ResponseMessage fail(String message){
        return new ResponseMessage(false, message, null);
    }

    /**
     * 失败返回方法
     * @param message 文字信息
     * @param data 数据
     */
    public static ResponseMessage fail(String message, Object data){
        return new ResponseMessage(false, message, data);
    }

}

开发者可以根据实际业务进行扩展次实体类,如增加时间戳、错误码等信息

推荐阅读更多精彩内容