spring boot controller返回值的统一处理

顾名思义,就是统一修改某些接口的返回值。在这之前,我们可能会发现我们的controller中有以下代码:

其中的BaseResult是基础的返回值,里面有errorCode、errorMsg和body属性,可能大部分接口都是这种返回值类型,然后我们需要在每个接口中手动捕捉异常,手动设置errorCode、errorMsg和body,这样我们就做了很多的重复工作,其实可以简化这些操作的,只需要下面几步就可以了:
第一、建立返回结果处理类

import java.lang.reflect.Method;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.xxx.blog.annotation.SysLog;
import com.xxx.blog.result.BaseResult;

@RestControllerAdvice
public class ResultHandler implements ResponseBodyAdvice<Object>{

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		Method method = returnType.getMethod();
		SysLog sysLog = method.getAnnotation(SysLog.class);
		if(sysLog != null) {
			// 只处理含有SysLog注解的方法
			return true;
		}
		return false;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
	    // 修改返回值类型
		BaseResult result = new BaseResult();
		result.setBody(body);
		return result;
	}

}

第二步、建立异常处理类

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 业务异常处理方法
	@ExceptionHandler(value = CommonException.class)
	public Object CommonException(HttpServletRequest request, CommonException e, HandlerMethod handlerMethod) {
		log.error("业务处理不成功,错误信息为:	{}", e.getMessage());
		Method method = handlerMethod.getMethod();
		if(method.getReturnType().equals(ModelAndView.class)) {
			String view = (String) request.getAttribute(SessionKey.ERROR_RETURN_PAGE);
			if(StringUtil.isNullOrEmpty(view)) {
				view = "/index";
			}
			return new ModelAndView(view);
		}
		return new BaseResult(e);
	}
	
	// 服务器异常处理方法
	@ExceptionHandler(value = Exception.class)
	public Object exception(HttpServletRequest request, Exception e, HandlerMethod handlerMethod) {
		log.error("服务器发生异常,异常信息为", e);
		Method method = handlerMethod.getMethod();
		if(method.getReturnType().equals(ModelAndView.class)) {
			String view = (String) request.getAttribute(SessionKey.ERROR_RETURN_PAGE);
			if(StringUtil.isNullOrEmpty(view)) {
				view = "/index";
			}
			return new ModelAndView(view);
		}
		return new BaseResult("服务器内部发生异常");
	}
	
}

这个时候我们的接口只需要这样写就可以了

@RequestMapping("/editor")
@SysLog("编辑留言")
public void editor(Feedback feedback) throws  CommonException{
	if(feedback == null || StringUtil.isNullOrEmpty(feedback.getContent())) {
		throw new CommonException("留言内容不能为空");
	}
	feedbackService.editor(feedback, null);
}

如果需要往BaseResult的body中设置值,则可写成:

@RequestMapping("/editor")
@SysLog("查询留言")
public Feedback editor(String id) throws CommonException {
	if(StringUtil.isNullOrEmpty(id)) {
		throw new CommonException("留言id不能为空");
	}
	return feedbackService.findById(id);
}

是不是发现简单多了呢?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值