springboot aop接口异常处理 统一打印日志

1、什么是aop, 它能做什么?

aop面向切面变成,面向切面简单理解就是对某一方面处理,类似拦截器,可以对拦截的数据、异常信息处理。譬如,日志记录,性能统计,安全控制,事务处理,异常处理等等。

组成:

advise通知:bofore前置通知、around环绕、after 后置通知、after returning 后置返回通知、after throwing异常通知(这些是我们能对应处理的通知事件)

另外还有,切点PointCut、Aspect切面、JoinPoint连接点等等概念

 2、aop接口异常处理

maven 配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sakyoka.test</groupId>
  <artifactId>springboot-aop-test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-aop-test</name>
  <url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- springboot start -->
		<!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> 
				<artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> -->
		</dependency>
		
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>	
		
		<dependency> 
		    <groupId>org.projectlombok</groupId> 
		    <artifactId>lombok</artifactId> 
		</dependency>
		
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.7</version>
		</dependency>
	</dependencies>


   <build>
        <finalName>springboot-websocket-log-test</finalName>
        <resources>
            <resource>
                <directory>${basedir}/src/main/webapp</directory>
                <!--注意此次必须要放在此目录下才能被访问到-->
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

aop类配置,这里只需要用到around环绕,对其ProceedingJoinPoint的proceed方法try..catch,在catch里面打印需要日志、异常信息返回封装。切点Pointcut对controller包的类方法拦截。

package com.sakyoka.test.aop;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import lombok.extern.log4j.Log4j;

/**
 * 
 * 描述:统一处异常、打印日志
 * @author sakyoka
 * @date 2022年8月20日 下午7:22:03
 */
@Component
@Aspect
@Log4j
public class ResultExceptionAop {
	 
    @Pointcut("execution(* com.sakyoka.test.controller.*.*(..))")
    public void result(){}
    
    @Around(value = "result()")
    public Object around(ProceedingJoinPoint point){    	
		try {
			return point.proceed();
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
    		String msg = (e instanceof ParamException ? e.getMessage(): "系统内部处理异常,请联系管理员");
    		// other exception message
			return ResultBean.builder()
					.code(ResultBean.INTERNAL_ERROR)
					.msg(msg)
					.data(ExceptionUtils.getStackTrace(e))
					.build();
		}
    }
}

测试接口类

package com.sakyoka.test.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sakyoka.test.aop.ParamException;
import com.sakyoka.test.aop.ResultBean;

/**
 * 
 * 描述:测试异常
 * @author sakyoka
 * @date 2022年8月20日 下午7:30:44
 */
@RestController
@RequestMapping("/test")
public class TestController {

	/**
	 * 
	 * 描述:测试异常
	 * @author sakyoka
	 * @date 2022年8月20日 下午7:32:27
	 * @return ResultBean<String>
	 */
	@GetMapping("/testException")
	public ResultBean<String> test(@RequestParam(name = "value", required = false)String value){
		if ("1".equals(value)) {
			throw new ParamException("测试异常,value = 1");
		}
		return ResultBean.ok(null);
	}
}

下面就是测试了

例子

例子

 aop接口异常测试完毕。另外可能有些前后端没有分离的,可以判断返回对象是数据对象还是视图对象进行返回,如果是视图统一跳转到错误页面就好了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用AOP(面向切面编程)来实现统一异常处理。下面是一个简单的示例: 首先,在你的Spring Boot项目中创建一个全局异常处理类,例如 `GlobalExceptionHandler`。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { // 处理异常逻辑 // 返回自定义的异常信息 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("发生异常,请联系管理员"); } } ``` 在上面的代码中,我们使用了 `@ControllerAdvice` 注解来标识全局异常处理类,并使用 `@ExceptionHandler` 注解来指定处理的异常类型。 接下来,我们需要在Spring Boot应用程序的入口类上添加 `@EnableAspectJAutoProxy` 注解以启用AOP功能。 ```java @SpringBootApplication @EnableAspectJAutoProxy public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 然后,创建一个切面类来捕获所有被 `@Controller` 或 `@RestController` 注解标识的类中抛出的异常,并将其委托给全局异常处理类进行处理。 ```java @Aspect @Component public class ExceptionAspect { @Autowired private GlobalExceptionHandler globalExceptionHandler; @Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)") public void controllerPointcut() {} @AfterThrowing(pointcut = "controllerPointcut()", throwing = "ex") public Object handleException(JoinPoint joinPoint, Exception ex) throws Throwable { return globalExceptionHandler.handleException(ex); } } ``` 在上面的代码中,我们使用 `@Aspect` 注解标识该类为切面类,并使用 `@Component` 注解将其作为Spring组件进行管理。 通过 `@Pointcut` 注解指定切入点,我们选择了所有被 `@Controller` 或 `@RestController` 注解标识的类。 在 `@AfterThrowing` 注解中,我们指定了切入点为 `controllerPointcut()`,并指定了异常类型为 `Exception`,在方法中调用全局异常处理类的方法进行异常处理。 这样,当被 `@Controller` 或 `@RestController` 注解标识的类中抛出异常时,切面类会捕获到异常并委托给全局异常处理类进行处理。 这就是使用AOP实现Spring Boot统一异常处理的基本步骤。你可以根据自己的需求进行扩展和定制化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值