lonsdale8734 2016-04-06 02:21 采纳率: 0%
浏览 2751

怎么包裹RestController的返回值?

例如原始返回值是 ”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";
    }
}
  • 写回答

1条回答

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-21 01:58
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!