秒杀第七节:定义通用的返回对象--异常处理

2020-07-22  本文已影响0人  小石读史

在上一节中我们说道如果只在controller层抛出异常在请求时会出现以下页面


image.png

那么怎么样才能返回给前端一个正确格式的错误信息呢。我们可以定义exceptionghandler解决为被controller层吸收的exception
在controller包下新建类BaseController

package com.miaoshaproject.controller;

import com.miaoshaproject.error.BussinessException;
import com.miaoshaproject.error.EmBusinessError;
import com.miaoshaproject.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";


    //定义exceptionghandler解决为被controller层吸收的exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex) {

        //必须自己封装data对象,否则data为exception反序列化的对象
        Map<String,Object> responseData = new HashMap<>();

        if(ex instanceof BussinessException){
            BussinessException bussinessException = (BussinessException) ex;
            responseData.put("errCode",bussinessException.getErrCode());
            responseData.put("errMsg",bussinessException.getErrMsg());
        } else {
            responseData.put("errCode", EmBusinessError.UNKNOW_ERROR.getErrCode());
            responseData.put("errMsg", EmBusinessError.UNKNOW_ERROR.getErrMsg());

        }
        return CommonReturnType.create(responseData,"fail");

    }
}

然后UserController extends BaseController。这个时候再次请求:http://localhost:8080/user/get?id=2
返回结果:{"status":"fail","data":{"errCode":20001,"errMsg":"用户不存在"}}

上一篇 下一篇

猜你喜欢

热点阅读