從零搭建自己的SpringBoot後臺框架(五)

Mr_初晨發表於2019-03-03
Hello大家好,本章我們新增全域性異常處理。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝

一:為什麼需要定義全域性異常

在網際網路時代,我們所開發的應用大多是直面使用者的,程式中的任何一點小疏忽都可能導致使用者的流失,而程式出現異常往往又是不可避免的,所以我們需要對異常進行捕獲,然後給予相應的處理,來減少程式異常對使用者體驗的影響

二:新增業務類異常

在前面說過的ret資料夾下建立ServiceException

package com.example.demo.core.ret;

import java.io.Serializable;

/**
 * @Description: 業務類異常
 * @author 張瑤
 * @date 2018/4/20 14:30
 * 
 */
public class ServiceException extends RuntimeException implements Serializable{

   private static final long serialVersionUID = 1213855733833039552L;

   public ServiceException() {
   }

   public ServiceException(String message) {
      super(message);
   }

   public ServiceException(String message, Throwable cause) {
      super(message, cause);
   }
}複製程式碼

三:新增異常處理配置

開啟上篇文章建立的WebConfigurer,新增如下方法

@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    exceptionResolvers.add(getHandlerExceptionResolver());
}

/**
 * 建立異常處理
 * @return
 */
private HandlerExceptionResolver getHandlerExceptionResolver(){
    HandlerExceptionResolver handlerExceptionResolver = new HandlerExceptionResolver(){
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                             Object handler, Exception e) {
            RetResult<Object> result = getResuleByHeandleException(request, handler, e);
            responseResult(response, result);
            return new ModelAndView();
        }
    };
    return handlerExceptionResolver;
}

/**
 * 根據異常型別確定返回資料
 * @param request
 * @param handler
 * @param e
 * @return
 */
private RetResult<Object> getResuleByHeandleException(HttpServletRequest request, Object handler, Exception e){
    RetResult<Object> result = new RetResult<>();
    if (e instanceof ServiceException) {
        result.setCode(RetCode.FAIL).setMsg(e.getMessage()).setData(null);
        return result;
    }
    if (e instanceof NoHandlerFoundException) {
        result.setCode(RetCode.NOT_FOUND).setMsg("介面 [" + request.getRequestURI() + "] 不存在");
        return result;
    }
    result.setCode(RetCode.INTERNAL_SERVER_ERROR).setMsg("介面 [" + request.getRequestURI() + "] 內部錯誤,請聯絡管理員");
    String message;
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        message = String.format("介面 [%s] 出現異常,方法:%s.%s,異常摘要:%s", request.getRequestURI(),
                handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod() .getName(), e.getMessage());
    } else {
        message = e.getMessage();
    }
    LOGGER.error(message, e);
    return result;
}

/**
 * @Title: responseResult
 * @Description: 響應結果
 * @param response
 * @param result
 * @Reutrn void
 */
private void responseResult(HttpServletResponse response, RetResult<Object> result) {
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-type", "application/json;charset=UTF-8");
    response.setStatus(200);
    try {
        response.getWriter().write(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue));
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
    }
}複製程式碼

四:新增配置檔案

Spring Boot 中, 當使用者訪問了一個不存在的連結時, Spring 預設會將頁面重定向到 **/error** 上, 而不會丟擲異常. 

既然如此, 那我們就告訴 Spring Boot, 當出現 404 錯誤時, 丟擲一個異常即可. 

application.properties 中新增兩個配置: 

spring.mvc.throw-exception-if-no-handler-found=true 

spring.resources.add-mappings=false 

上面的配置中, 第一個 spring.mvc.throw-exception-if-no-handler-found 告訴 SpringBoot 當出現 404 錯誤時, 直接丟擲異常. 第二個 spring.resources.add-mappings 告訴 SpringBoot 不要為我們工程中的資原始檔建立對映.

五:建立測試介面

package com.example.demo.service.impl;

import com.example.demo.core.ret.ServiceException;
import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 張瑤
 * @Description:
 * @time 2018/4/18 11:56
 */
@Service
public class UserInfoServiceImpl implements UserInfoService{

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo selectById(Integer id){
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null){
            throw new ServiceException("暫無該使用者");
        }
        return userInfo;
    }
}複製程式碼

UserInfoController.java

package com.example.demo.controller;

import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.ret.ServiceException;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 張瑤
 * @Description:
 * @time 2018/4/18 11:39
 */
@RestController
@RequestMapping("userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello(){
        return "hello SpringBoot";
    }

    @PostMapping("/selectById")
    public RetResult<UserInfo> selectById(Integer id){
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    }

    @PostMapping("/testException")
    public RetResult<UserInfo> testException(Integer id){
        List a = null;
        a.size();
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    }


}複製程式碼

六:介面測試

訪問192.168.1.104:8080/userInfo/selectById引數 id:3

{
    "code": 400,
    "data": null,
    "msg": "暫無該使用者"
}複製程式碼

訪問192.168.1.104:8080/userInfo/testException

{
    "code": 500,
    "data": null,
    "msg": "介面 [/userInfo/testException] 內部錯誤,請聯絡管理員"
}複製程式碼

專案地址

碼雲地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

寫文章不易,如對您有幫助,請幫忙點下star從零搭建自己的SpringBoot後臺框架(五)

結尾

springboot新增全域性異常處理已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。


相關文章