SpringBoot RestController 自定义404返回数据

最近做前后端分离的项目,有时候前端接口写错了就会返回一个JSON数据

{
  "timestamp": 1492063521109,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/restapi/xxx"
}

但这与我之前正常接口返回的数据格式不统一,我需要自定义返回数据。

SpringBoot有一个默认的Controller来处理这些错误:BasicErrorController

摘录一下BasicErrorController中的关键代码。

@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
    
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity(status);
        } else {
            Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
            return new ResponseEntity(body, status);
        }
    }
}

BasicErrorController继承AbstractErrorController,而AbstractErrorController实现了ErrorController。

其实说白了,只需要实现ErrorController就可以了。

直接给个示例吧。

@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class MyErrorController implements ErrorController {

    @RequestMapping
    public Resp error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        Resp resp = new Resp();
        resp.setCode(status.value());
        if (HttpStatus.NOT_FOUND.equals(status)) {
            resp.setMessage("请求资源不存在");
        } else if (HttpStatus.UNAUTHORIZED.equals(status)) {
            resp.setMessage("账号权限不足");
        }
        return resp;
    }

    public HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }

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

只对404和401的错误进行了处理。

上一篇:卡尔曼滤波的原理(Python实现)


下一篇:机器学习-线性回归