Skip to main content

03.SprintBoot异常处理

1 什么是异常?

程序,程序,就是按照设定好的方式进行处理,但凡事在结果出来前总有意外,程序在处理的过程中,由于各种原因,可能发生程序预期外的情况出现,从而导致 程序错误或中断而取不到期待的结果。这种情况,就称为异常。

2 SpringBoot 异常处理示例

package com.zhuche.server.core;

import com.zhuche.server.core.configuration.ExceptionCodeConfiguration;
import com.zhuche.server.exception.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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 org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice // <-- 这个注解告诉SpringBoot 这里是异常处理类
public class GlobalExceptionAdvice {

@Autowired
private ExceptionCodeConfiguration _exceptionCodeConfiguration;

@ExceptionHandler(value = Exception.class) // <-- 处理默认异常,没有指定的话,都通过这里来处理
@ResponseBody
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public UnifyResponse handleException(HttpServletRequest req, Exception e) {
String url = req.getRequestURI();
String method = req.getMethod();
System.out.println(e);

return new UnifyResponse(9999, "服务器内部错误", method + " " + url);
}

@ExceptionHandler(HttpException.class) // <-- 指定异常处理
public ResponseEntity handleHttpException(HttpServletRequest req, HttpException e) {
String requestUrl = req.getRequestURI();
String method = req.getMethod();
UnifyResponse message = new UnifyResponse(e.getCode(), this._exceptionCodeConfiguration.getMessage(e.getCode()), method + " " + requestUrl);
HttpHeaders headers = new HttpHeaders();
HttpStatus status = HttpStatus.resolve(e.getHttpStatusCode());
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<UnifyResponse> res = new ResponseEntity<UnifyResponse>(message, headers, status);

return res;
}
}