例如原始返回值是 ”This is response“,
返回
{
"status":1,
"content":"This is response”
}
异常时返回
{
"status":0,
"content":"exception message”
}
使用spring aop没有实现预期的结果
@Component
@Aspect
@EnableAspectJAutoProxy
public class ResponseWrapping {
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restPointcut() {
}
@Pointcut("execution(* *(..))")
public void anyMethodPointcut() {
}
@AfterReturning(value = "restPointcut() && anyMethodPointcut()", returning = "response")
public Object wrapResponse(Object response) {
Map<String, Object> result = new HashMap<>();
result.put("status", 1);
result.put("data", response);
return result;
}
@AfterThrowing(value = "restPointcut() && anyMethodPointcut()", throwing = "exception")
public Object wrapException(RuntimeException exception) {
Map<String, Object> result = new HashMap<>();
result.put("status", 0);
result.put("msg", exception.getMessage());
return result;
}
}
测试用controller
@RestController
@RequestMapping("/admin")
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Object test(@RequestParam("test") int test) {
if (test == 0)
throw new RuntimeException("This is an exception test response");
else
return "This is normal test response";
}
}