spring mvc + aop 進行業務異常處理

如果不喜歡寫aop的,可以使用@ControllerAdvice註解來替代,形式如下,@ExceptionHandler代表接入點,ExceptionConfigController代表切面

@ControllerAdvice
public class ExceptionConfigController {
    // 專門用來捕獲和處理Controller層的空指針異常
    @ExceptionHandler(BusinessException.class)
    public void BusinessExceptionHandler(BusinessException business,
                                         HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        Gson gson = new Gson();
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(gson.toJson(new ReturnType(business.getEnumNeedInterFace())).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

如果需要使用傳統方法的可以自己定義切面指定切點

@Aspect
@Component
public class ExceptionAopAction {
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void pointCut(){}
    @AfterThrowing(pointcut = "pointCut()", throwing = "business")
    public void BusinessExceptionHandler(BusinessException business) throws IOException {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        Gson gson = new Gson();
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(gson.toJson(new ReturnType(business.getEnumNeedInterFace())).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章