1. 程式人生 > >shiro與spring security如何用自定義異常處理401

shiro與spring security如何用自定義異常處理401

背景

現在是前後端分離的時代,後端必然要統一處理返回結果,比如定義一個返回物件

public class ResponseData<T> {
    /**
     * 統一返回碼
     */
    public String rtnCode;

    /**
     * 統一錯誤訊息
     */
    public String rtnMsg;

    /**
     * 結果物件
     */
    public T rtnData;

對於所有異常都有對應的rtnCode對應,而不需要框架預設處理如返回
在這裡插入圖片描述

這時候前端同學就不開心了,都已經有rtnCode了,為啥http的status還要弄個401而不是200。

解決方案

一般的業務異常在springboot專案中新建一個統一處理類去處理即可,如

@ControllerAdvice
public class DefaultExceptionHandler {

    /**
     * 異常統一處理
     */
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseData allException(Exception e) {

大部分情況都能捕獲到從而如期返回json物件資料,但是某些許可權框架丟擲的異常如401等等,不會被攔截到,這時候就需要再建一個類去處理這種情況,程式碼如下

package com;

import com.vo.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * spring security 異常處理
 */
@RestController
public class CustomErrorController implements ErrorController {
	private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = PATH)
    ResponseData error(HttpServletRequest request, HttpServletResponse response) {
        // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring. 
        // Here we just define response body.
    	Map<String, Object> errorMap = getErrorAttributes(request);
        ResponseData d= new ResponseData(response.getStatus()+"", errorMap.get("message").toString());
        response.setStatus(HttpServletResponse.SC_OK);
        return d;
    }

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

    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return errorAttributes.getErrorAttributes(requestAttributes, false);
    }
    

}