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();
    }
}

你可能感兴趣的:(java)