這篇文章主要介紹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);
}
}最近在用springboot整合shiro,在訪問時出現了No SecurityManager accessible to the calling code…
報錯:


自定義的SysUserFilter加載順序在ShiroFilter之前,導致出現No SecurityManager accessible to the calling code…

shiroFilter()的加載先于自定義的SysUserFilter
以上是“shiro與spring security怎么用自定義異常處理401錯誤”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。