赞
踩
今天遇到一个需求,在不改动原系统代码的情况下。将Controller的返回值和异常包装到一个统一的返回对象中去。
例如原系统的接口
public String myIp(@ApiIgnore HttpServletRequest request);
返回的只是一个IP字符串"0:0:0:0:0:0:0:1",目前接口需要包装为:
{"code":200,"message":"","result":"0:0:0:0:0:0:0:1","success":true}
而原异常跳转到error页面,需要调整为
{
"success": false,
"message": "For input string: \"fdsafddfs\"",
"code": 500,
"result": "message"
}
因此就有了2个工作子项需要完成:
1)Exception的处理
2)controller return值的处理
返回的exception处理可以采用@RestControllerAdvice来处理。
建立自己的Advice类,注入国际化资源(异常需要支持多语言)
- package org.ccframe.commons.mvc;
-
- import lombok.extern.log4j.Log4j2;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.http.HttpStatus;
- import org.ccframe.commons.filter.CcRequestLoggingFilter;
- import org.ccframe.commons.util.BusinessException;
- import org.ccframe.config.GlobalEx;
- import org.ccframe.subsys.core.dto.Result;
- import org.springframework.context.MessageSource;
- import org.springframework.context.NoSuchMessageException;
- import org.springframework.core.MethodParameter;
- import org.springframework.http.ResponseEntity;
- import org.springframework.orm.ObjectOptimisticLockingFailureException;
- import org.springframework.web.HttpRequestMethodNotSupportedException;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.context.request.NativeWebRequest;
- import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
- import org.springframework.web.method.support.ModelAndViewContainer;
- import org.springframework.web.multipart.MaxUploadSizeExceededException;
- import org.springframework.web.servlet.LocaleResolver;
- import org.springframework.web.servlet.NoHandlerFoundException;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.Locale;
-
- @RestControllerAdvice
- @Log4j2
- public class GlobalRestControllerAdvice{
-
- private MessageSource messageSource; //国际化资源
-
- private LocaleResolver localeResolver;
-
- private Object[] EMPTY_ARGS = new Object[0];
-
- public GlobalRestControllerAdvice(MessageSource messageSource, LocaleResolver localeResolver){
- this.messageSource = messageSource;
- this.localeResolver = localeResolver;
- }
-
- private Result<String> createError(HttpServletRequest request, Exception e,int code, String msgKey, Object[] args){
- Locale currentLocale = localeResolver.resolveLocale(request);
- String message = "";
- try {
- message = messageSource.getMessage(msgKey, args, currentLocale);
- }catch (NoSuchMessageException ex){
- message = e.getMessage();
- }finally {
- log.error(message);
- CcRequestLoggingFilter.pendingLog(); //服务器可以记录出错时的请求啦声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/229669推荐阅读
相关标签
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。