自定义ResponseResult在controller响应信息主体和自定义全局及局部异常中的实现

Posted 阿啄debugIT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义ResponseResult在controller响应信息主体和自定义全局及局部异常中的实现相关的知识,希望对你有一定的参考价值。

前言:

在controller及hanlder的消息返回给客户端的json对象信息,一般是自定义的,输出格式是json格式!

自定义详细编号HttpEnum

/**
 * <b><code>HttpEnum</code></b>
 * <p>
 * Description
 * </p>
 * <b>Creation Time:</b> 2019/11/26 16:21.
 *
 */
public enum HttpEnum 
    /**
     * 请求处理正常
     */
    OK_200(200, "请求成功"),

    /**
     * 请求处理正常
     */
    CREATED_201(201, "创建成功"),


    /**
     * 请求处理异常,请稍后再试
     */
    ERROR_400(400, "非法请求"),

    /**
     * 访问内容不存在
     */
    NotFound_400(404, "访问内容不存在"),

    /**
     * 系统内部错误
     */
    ERROR_500(500, "系统内部错误"),

    /**
     * 参数校验失败
     */
    ERROR_600(600, "参数校验失败");

    private String desc;

    private int code;

    private HttpEnum(int code, String desc) 
        this.desc = desc;
        this.code = code;
    

    public String desc() 
        return desc;
    

    public int code() 
        return code;
    

自定义响应的信息主体ResponseResult

import java.io.Serializable;

import com.a.b.c.commons.enums.HttpEnum;

import lombok.Getter;
import lombok.Setter;

/**
 * <b><code>ResponseResult</code></b>
 * <p>
 * Description响应信息主体
 * </p>
 * <b>Creation Time:</b> 2019/11/26 17:55.
 *
 * @author chensen
 * @since gempile-boiler-code 0.1.0
 */
public class ResponseResult<T> implements Serializable 
    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String msg;

    @Getter
    @Setter
    private T data;

    public static <T> ResponseResult<T> ok() 
        return restResult(null, HttpEnum.OK_200.code(), HttpEnum.OK_200.desc());
    

    public static <T> ResponseResult<T> ok(T data) 
        return restResult(data, HttpEnum.OK_200.code(), HttpEnum.OK_200.desc());
    

    public static <T> ResponseResult<T> ok(T data, String msg) 
        return restResult(data, HttpEnum.OK_200.code(), msg);
    

    public static <T> ResponseResult<T> failed() 
        return restResult(null, HttpEnum.ERROR_500.code(),
                HttpEnum.ERROR_500.desc());
    

    public static <T> ResponseResult<T> failed(String msg) 
        return restResult(null, HttpEnum.ERROR_500.code(), msg);
    

    public static <T> ResponseResult<T> failed(int code, String msg) 
        return restResult(null, code, msg);
    

    public static <T> ResponseResult<T> failed(T data) 
        return restResult(data, HttpEnum.ERROR_500.code(),
                HttpEnum.ERROR_500.desc());
    

    public static <T> ResponseResult<T> failed(T data, String msg) 
        return restResult(data, HttpEnum.ERROR_500.code(), msg);
    

    private static <T> ResponseResult<T> restResult(T data, int code,
                                                    String msg) 
        ResponseResult<T> apiResult = new ResponseResult<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    

ResponseResult在Handler中的应用

处理异常

在应用开发过程中,除系统自身的异常外,不同业务场景中用到的异常也不一样,为了与标题 轻松搞定全局异常 更加的贴切,定义个自己的异常,看看如何捕获…

  • @ControllerAdvice 捕获 Controller 层抛出的异常,如果添加 @ResponseBody 返回信息则为JSON格式。
  • @RestControllerAdvice 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
  • @ExceptionHandler 统一处理一种类的异常,减少代码重复率,降低复杂度。

创建全局异常

创建一个 GlobalExceptionHandler 类,并添加上 @RestControllerAdvice 注解就可以定义出异常通知类了,然后在定义的方法中添加上 @ExceptionHandler 即可实现异常的捕捉…

GlobalExceptionHandler 类

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSONObject;
import com.a.b.c.commons.enums.HttpEnum;
import com.a.b.c.commons.util.ResponseResult;

import lombok.extern.slf4j.Slf4j;

/**
 * <b><code>GlobalExceptionHandler</code></b>
 * <p>
 * Description
 * </p>
 * <b>Creation Time:</b> 2019/11/26 16:17.
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler 
    /**
     * 全局异常.
     *
     * @param e the e
     * @return ResponseResult
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception e) 
        log.error("全局异常信息 ex=", e.getMessage(), e);
        JSONObject errorObject = new JSONObject();
        errorObject.put("errorInfo", e.toString());
        // 如果错误堆栈信息存在
        if (e.getStackTrace().length > 0) 
            StackTraceElement element = e.getStackTrace()[0];
            int lineNumber = element.getLineNumber();
            errorObject.put("errorPosition", element + ":" + lineNumber);
        
        return ResponseResult.failed(errorObject);
    

    /**
     * 自定义异常处理
     * @param e
     * @return ResponseResult
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult customExceptionHandLer(CustomException e) 
        return ResponseResult.failed(e.getCode(), e.getDesc());
    

    /**
     * 校验异常 Exception
     *
     * @param exception
     * @return ResponseResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class, BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult bodyValidExceptionHandler(MethodArgumentNotValidException exception) 
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        String errorMessage="";
        if(fieldErrors!=null&&fieldErrors.size()>0)
            log.warn(fieldErrors.get(0).getDefaultMessage());
            errorMessage=fieldErrors.get(0).getDefaultMessage();
        
        return ResponseResult.failed(HttpEnum.ERROR_600.code(), errorMessage);
    


出现404或者405等错误信息

ErrorController当系统出现404或者405等错误信息时,springboot默认的访问路径为/error,所以实现ErrorController并重写

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.a.b.c.commons.enums.HttpEnum;
import com.a.b.c.commons.util.ResponseResult;

/**
 * <b><code>NotFoundException</code></b>
 * <p>
 * Description
 * </p>
 * <b>Creation Time:</b> 2019/12/4 14:15.
 *
 */
@RestController
public class NotFoundException implements ErrorController 

    @Override
    public String getErrorPath() 
        return "/error";
    

    @RequestMapping(value = "/error")
    public ResponseResult error(HttpServletRequest request) 
        return ResponseResult.failed(HttpEnum.NotFound_400.code(), HttpEnum.NotFound_400.desc());
    

在controller中的应用

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.a.b.c.entity.common.GAppDetailInfo;
import com.a.b.c.entity.indicator.GAppIndicator;
import com.a.b.c.mapper.common.GIndicatorQueryMapper;
import com.a.b.c.service.common.GComonConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.a.b.c.commons.util.DateUtils;
import com.a.b.c.commons.util.ResponseResult;
import com.a.b.c.service.alarm.GAlarmQueryService;

import io.swagger.annotations.*;

/**
 * <b><code>GCommonConfigController</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 2019/12/7 11:22.
 *
 */
@SuppressWarnings("MagicConstant")
@RestController
@RequestMapping("/v1.0")
@Api(value = "[Gpile-voiler 1.0]通用配置查询")
public class GCommonConfigController 

    /**
     * logger.
     */
    private static Logger logger = LoggerFactory.getLogger(GCommonConfigController.class);

    /**
     * The gmp alarm query statistics service.
     */
    @Autowired
    private GAlarmQueryService GAlarmQueryService;

    @Autowired
    private GComonConfigService GComonConfigService;

    /**
     * get app indicator.
     */
    @RequestMapping(value = "/config/indicators", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "[Gpile-boiler]指标查询", notes = "get indicators")
    @ApiResponses(value = 
            @ApiResponse(code = 200, message = "successful query", response = Integer.class, responseContainer = "int"),
            @ApiResponse(code = 500, message = "internal server error") )
    public ResponseResult getAlertResult(
            @ApiParam(value = "应用code") @RequestParam(value = "appCode") String appCode,
            @ApiParam(value = "模块id") @RequestParam(value = "module",required = false) String module,
            @ApiParam(value = "维度id") @RequestParam(value = "dimension",  required = false) String dimension
            ) 

        List<GAppIndicator> results= GComonConfigService.selectIndicatorByParm(appCode,module,dimension);
        return ResponseResult.ok(results);
    

    /**
     * get app detail info.
     */
    @RequestMapping(value = "/config/appDetailInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "[Gpile-boiler]设备信息查询", notes = "get app detail info")
    @ApiResponses(value = 
            @ApiResponse(code = 200, message = "successful query", response = Integer.class, responseContainer = "int"),
            @ApiResponse(code = 500, message = "internal server error") )
    public ResponseResult getAlertResult(
            @ApiParam(value = "应用code") @RequestParam(value = "appCode") String appCode,
            @ApiParam(value = "设备code") @RequestParam(value = "deviceCode",required = false) Long deviceCode
            ) 

        List<GAppDetailInfo> results= GComonConfigService.selectDeviceInfoByAppCode(appCode,deviceCode,null);
        return ResponseResult.ok(results);
    

 

 

 

 

 

以上是关于自定义ResponseResult在controller响应信息主体和自定义全局及局部异常中的实现的主要内容,如果未能解决你的问题,请参考以下文章

springboot自定义注解AOP在controller上时导致controller注入失败的问题

在 View Controller 中引用自定义视图时出错

[翻译]Writing Custom Common Controls 编写自定义控件

GET:ParamsResponse

自定义 UIView 在 View Controller 中被解包为 nil

spring的全局自定义异常案例「完美拦截Controller层全部异常」