这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
写一个拦截器,在程序发生异常的时候可以捕获到并将异常打印出来
首先是定义一个拦截器,这里的拦截器名为HandleError,注意要用InterceptorBinding修饰
package com.bolingcavalry.interceptor.define;
import javax.interceptor.InterceptorBinding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
@InterceptorBinding
@Target({TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface HandleError {
}
package com.bolingcavalry.interceptor.impl;
import com.bolingcavalry.interceptor.define.HandleError;
import io.quarkus.arc.Priority;
import io.quarkus.logging.Log;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@HandleError
@Interceptor
@Priority(Interceptor.Priority.APPLICATION +1)
public class HandleErrorInterceptor {
@AroundInvoke
Object execute(InvocationContext context) {
try {
// 注意proceed方法的含义:调用下一个拦截器,直到最后一个才会执行被拦截的方法
return context.proceed();
} catch (Exception exception) {
Log.errorf(exception,
"method error from %s.%s\n",
context.getTarget().getClass().getSimpleName(),
context.getMethod().getName());
}
return null;
}
}
@ApplicationScoped
@HandleError
public class HandleErrorDemo {
public void executeThrowError() {
throw new IllegalArgumentException("this is business logic exception");
}
}
@QuarkusTest
public class InterceptorTest {
@Inject
HandleErrorDemo handleErrorDemo;
@Test
public void testHandleError() {
handleErrorDemo.executeThrowError();
}
}
@InterceptorBinding
@Target({TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface HandleConstruction {
}
@HandleConstruction
@Interceptor
@Priority(Interceptor.Priority.APPLICATION +1)
public class HandleConstructionInterceptor {
@AroundConstruct
void execute(InvocationContext context) throws Exception {
// 执行业务逻辑可以在此
Log.infov("start construction interceptor");
// 执行bean的构造方法
context.proceed();
// 注意,对于context.getTarget()的返回值,此时不是null,如果在context.proceed()之前,则是null
Log.infov("bean instance of {0}", context.getTarget().getClass().getSimpleName());
}
}
@ApplicationScoped
@HandleConstruction
public class HandleonstructionDemo {
public HandleonstructionDemo() {
super();
Log.infov("construction of {0}", HandleonstructionDemo.class.getSimpleName());
}
public void hello() {
Log.info("hello world!");
}
}
@QuarkusTest
public class InterceptorTest {
@Inject
HandleonstructionDemo handleonstructionDemo;
@Test
public void testHandleonstruction() {
handleonstructionDemo.hello();
}
}
2022-03-27 15:51:03,158 INFO [io.quarkus] (main) Quarkus 2.7.3.Final on JVM started in 0.867s. Listening on: http://localhost:8081
2022-03-27 15:51:03,158 INFO [io.quarkus] (main) Profile test activated.
2022-03-27 15:51:03,158 INFO [io.quarkus] (main) Installed features: [agroal, cdi, narayana-jta, resteasy, smallrye-context-propagation, vertx]
2022-03-27 15:51:03,164 INFO [com.bol.int.dem.HandleonstructionDemo] (main) construction of HandleonstructionDemo
2022-03-27 15:51:03,397 INFO [com.bol.int.imp.HandleConstructionInterceptor] (main) start construction interceptor
2022-03-27 15:51:03,398 INFO [com.bol.int.dem.HandleonstructionDemo] (main) construction of HandleonstructionDemo
2022-03-27 15:51:03,398 INFO [com.bol.int.imp.HandleConstructionInterceptor] (main) bean instance of HandleonstructionDemo
2022-03-27 15:51:03,398 INFO [com.bol.int.dem.HandleonstructionDemo] (main) hello world!
2022-03-27 15:51:03,416 INFO [io.quarkus] (main) Quarkus stopped in 0.015s
@InterceptorBinding
@Target({TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackParams {
}
@TrackParams
@Interceptor
@Priority(Interceptor.Priority.APPLICATION + 1)
public class TrackParamsInterceptor {
@AroundInvoke
Object execute(InvocationContext context) throws Exception {
// context.getParameters()返回拦截方法的所有参数,
// 用Optional处理非空时候的数组
Optional.of(Arrays.stream(context.getParameters()))
.ifPresent(stream -> {
stream.forEach(object -> Log.infov("parameter type [{0}], value [{1}]",
object.getClass().getSimpleName(),
object)
);
});
return context.proceed();
}
}
@ApplicationScoped
@TrackParams
public class TrackParamsDemo {
public void hello(String name, int id) {
Log.infov("Hello {0}, your id is {1}", name, id);
}
}
@QuarkusTest
public class InterceptorTest {
@Inject
TrackParamsDemo trackParamsDemo;
@Test
public void testTrackParams() {
trackParamsDemo.hello("Tom", 101);
}
}
2022-03-27 17:15:46,582 INFO [io.quarkus] (main) Quarkus 2.7.3.Final on JVM started in 0.905s. Listening on: http://localhost:8081
2022-03-27 17:15:46,582 INFO [io.quarkus] (main) Profile test activated.
2022-03-27 17:15:46,582 INFO [io.quarkus] (main) Installed features: [agroal, cdi, narayana-jta, resteasy, smallrye-context-propagation, vertx]
2022-03-27 17:15:46,587 INFO [com.bol.int.dem.HandleonstructionDemo] (main) construction of HandleonstructionDemo
2022-03-27 17:15:46,827 INFO [com.bol.int.imp.TrackParamsInterceptor] (main) parameter type [String], value [Tom]
2022-03-27 17:15:46,827 INFO [com.bol.int.imp.TrackParamsInterceptor] (main) parameter type [Integer], value [101]
2022-03-27 17:15:46,827 INFO [com.bol.int.dem.TrackParamsDemo] (main) Hello Tom, your id is 101
2022-03-27 17:15:46,845 INFO [io.quarkus] (main) Quarkus stopped in 0.015s
@InterceptorBinding
@Target({TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContextData {
String KEY_PROCEED_INTERCEPTORS = "proceedInterceptors";
}
package com.bolingcavalry.interceptor.impl;
import io.quarkus.logging.Log;
import javax.interceptor.InvocationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.bolingcavalry.interceptor.define.ContextData.KEY_PROCEED_INTERCEPTORS;
public class BaseContextDataInterceptor {
Object execute(InvocationContext context) throws Exception {
// 取出保存拦截器间共享数据的map
Map<String, Object> map = context.getContextData();
List<String> list;
String instanceClassName = this.getClass().getSimpleName();
// 根据指定key从map中获取一个list
if (map.containsKey(KEY_PROCEED_INTERCEPTORS)) {
list = (List<String>) map.get(KEY_PROCEED_INTERCEPTORS);
} else {
// 如果map中没有,就在此新建一个list,存如map中
list = new ArrayList<>();
map.put(KEY_PROCEED_INTERCEPTORS, list);
Log.infov("from {0}, this is first processor", instanceClassName);
}
// 将自身内容存入list中,这样下一个拦截器只要是BaseContextDataInterceptor的子类,
// 就能取得前面所有执行过拦截操作的拦截器
list.add(instanceClassName);
Log.infov("From {0}, all processors {0}", instanceClassName, list);
return context.proceed();
}
}
@ContextData
@Interceptor
@Priority(Interceptor.Priority.APPLICATION + 1)
public class ContextDataInterceptorA extends BaseContextDataInterceptor {
@AroundInvoke
Object execute(InvocationContext context) throws Exception {
return super.execute(context);
}
}
@ContextData
@Interceptor
@Priority(Interceptor.Priority.APPLICATION + 2)
public class ContextDataInterceptorB extends BaseContextDataInterceptor {
@AroundInvoke
Object execute(InvocationContext context) throws Exception {
return super.execute(context);
}
}
@ApplicationScoped
@ContextData
public class ContextDataDemo {
public void hello() {
Log.info("Hello world!");
}
}
@QuarkusTest
public class InterceptorTest {
@Inject
ContextDataDemo contextDataDemo;
@Test
public void testContextData() {
contextDataDemo.hello();
}
}
2022-03-27 23:29:27,703 INFO [io.quarkus] (main) Quarkus 2.7.3.Final on JVM started in 0.903s. Listening on: http://localhost:8081
2022-03-27 23:29:27,703 INFO [io.quarkus] (main) Profile test activated.
2022-03-27 23:29:27,703 INFO [io.quarkus] (main) Installed features: [agroal, cdi, narayana-jta, resteasy, smallrye-context-propagation, vertx]
2022-03-27 23:29:27,708 INFO [com.bol.int.dem.HandleonstructionDemo] (main) construction of HandleonstructionDemo
2022-03-27 23:29:27,952 INFO [com.bol.int.imp.BaseContextDataInterceptor] (main) from ContextDataInterceptorA, this is first processor
2022-03-27 23:29:27,953 INFO [com.bol.int.imp.BaseContextDataInterceptor] (main) From ContextDataInterceptorA, all processors ContextDataInterceptorA
2022-03-27 23:29:27,953 INFO [com.bol.int.imp.BaseContextDataInterceptor] (main) From ContextDataInterceptorB, all processors ContextDataInterceptorB
2022-03-27 23:29:27,953 INFO [com.bol.int.dem.ContextDataDemo] (main) Hello world!
2022-03-27 23:29:27,971 INFO [io.quarkus] (main) Quarkus stopped in 0.015s
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |