SpringBoot统一异常处理
自定义异常以及异常信息类:
package top.yibobo.hospital.exception; public class HospitalException extends Exception { public HospitalException(String message){ super(message); } }
package top.yibobo.hospital.domain; public class ErrorInfo<T> { public static final int OK = 0; public static final int ERROR = 100; private int code; private String message; private String url; private T data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
最关键的:统一异常处理,做异常处理的好处就是前台访问服务器时出现异常时
只会返回自定义的异常信息JSON
不会对其他功能造成影响
package top.yibobo.hospital.controller; 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 top.yibobo.hospital.domain.ErrorInfo; import top.yibobo.hospital.exception.HospitalException; import javax.servlet.http.HttpServletRequest; @ControllerAdvice//只要Controller出现异常,就会由这个类来处理 public class ExcptionController { @ResponseBody @ExceptionHandler(value = HospitalException.class)//对HospitalException这个异常进行处理 public ResponseEntity<?> hanlerExcption(HttpServletRequest request, HospitalException e)throws Exception{ ErrorInfo<String> error = new ErrorInfo<>(); error.setCode(ErrorInfo.ERROR); error.setMessage(e.getMessage()); error.setUrl(request.getRequestURL().toString()); error.setData("some data"); return new ResponseEntity<ErrorInfo>(error, HttpStatus.OK); } }