为什么会有这篇文章

前后端拆散零碎,应用SpringBoot搭建后端。
心愿申请后果能够依照HttpStatus返回。
搜寻了不少对于SpringBoot的全局异样解决,大部分都是返回200,再在音讯体中退出code,感觉这样解决不符合规范,所以有了以下内容。

步骤

  1. 创立异样类
  2. 创立全局异样解决
  3. 异样应用下面创立的异样类抛出

代码

异样类 BizException
该异样类应用最简略构造,仅有状态码和自定义信息,可依据本人须要拓展。

import org.springframework.http.HttpStatus;/** * 错误处理类 */public class BizException extends RuntimeException {    private HttpStatus status;    private String message;    public BizException(HttpStatus status, String message) {        super(message);        this.status = status;        this.message = message;    }    public BizException(HttpStatus status) {        this(status, status.getReasonPhrase());    }    public HttpStatus getStatus() {        return status;    }    @Override    public String getMessage() {        return message;    }}

全局异样解决 GlobalExceptionHandler
该类会依据抛出类型,主动进入对应解决类。

import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;/** * 全局异样解决 */@ControllerAdvicepublic class GlobalExceptionHandler {    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);    @ExceptionHandler(value = BizException.class)    @ResponseBody    public ResponseEntity<Map<String, Object>> bizExceptionHandler(HttpServletRequest req, BizException e) {        Map<String, Object> map = new HashMap<>();        map.put("message", e.getMessage());        return new ResponseEntity<>(map, e.getStatus());    }    @ExceptionHandler(value = Exception.class)    @ResponseBody    public ResponseEntity<Map<String, Object>> exceptionHandler(HttpServletRequest req, Exception e) {        Map<String, Object> map = new HashMap<>();        map.put("message", e.getMessage());        return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);    }}

在任意想要的中央抛出BizException异样

throw new BizException(HttpStatus.UNAUTHORIZED);throw new BizException(HttpStatus.UNAUTHORIZED,"未登录");

申请对应连贯,能够察看到状态码已变更为401,并附有信息

参考资料:
小白的springboot之路(十)、全局异样解决 - 大叔杨 - 博客园
小白的springboot之路(十一)、构建后盾RESTfull API
springboot自定义http反馈状态码 - Boblim - 博客园

首发于知乎
SpringBoot 全局异样解决