版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HSH205572/article/details/84620855
demo:
controller层:
package com.jkinfo.api.controller; import com.jkinfo.api.common.response.ApiResponse; import com.jkinfo.support.enums.LogTypeEnum; import com.jkinfo.support.enums.PopulationApiNameEnum; import com.jkinfo.system.service.ISysLogService; import org.apache.commons.lang3.StringUtils; 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.MissingServletRequestParameterException; 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; /** * 描述 ***接口 * * @author *** * @date 2018/11/28 */ @RestController @RequestMapping("/api/population") public class PopulationApiController { private static final Logger logger = LoggerFactory.getLogger(PopulationApiController.class); @Autowired ISysLogService sysLogService; /** * 描述 *** * * @param idCard * @return ApiResponse * @author *** * @date 2018/11/28 */ @RequestMapping(value = "/getIdentityInformationByIdCard", method = {RequestMethod.GET, RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ApiResponse getIdentityInformationByIdCard(@RequestParam(value = "idCard") String idCard) throws Exception { boolean bool = StringUtils.isBlank(idCard); if (bool) { throw new MissingServletRequestParameterException("idCard", "String"); } // 业务代码 return ApiResponse.success(null); } }
advice异常处理:
package com.jkinfo.api.common.advice; import com.alibaba.fastjson.JSON; import com.jkinfo.api.common.response.ApiResponse; import com.jkinfo.framework.tools.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * 描述 ***接口异常处理 * * @author *** * @date 2018/11/28 */ @ControllerAdvice("com.jkinfo.api.controller")//此处指定异常处理范围 public class ApiControllerAdvice { private static final Logger logger = LoggerFactory.getLogger(ApiControllerAdvice.class); @ExceptionHandler(Exception.class) public void handle(HttpServletResponse response, Exception ex) { ApiResponse result; //响应状态此处默认设置 INTERNAL_SERVER_ERROR(500, "Internal Server Error") //具体可根据需要在各异常类型下重新赋值 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; if (ex instanceof MissingServletRequestParameterException) { result = ApiResponse.error( ApiResponse.FAIL_MISS_PARAM_CODE, ApiResponse.FAIL_MISS_PARAM_MSG + ":" + ((MissingServletRequestParameterException) ex).getParameterName() ); // 重新设置响应状态 httpStatus = HttpStatus.BAD_REQUEST; } else if (ex instanceof MethodArgumentTypeMismatchException) { String description = StringUtils.assemblyString( "参数名:", ((MethodArgumentTypeMismatchException) ex).getName(), ",期望参数类型:", String.valueOf(((MethodArgumentTypeMismatchException) ex).getRequiredType()) ); result = ApiResponse.error( ApiResponse.FAIL_MISMATCH_PARAM_TYPE_CODE, ApiResponse.FAIL_MISMATCH_PARAM_TYPE_MSG + ":" + description ); // 重新设置响应状态 httpStatus = HttpStatus.BAD_REQUEST; } else { result = ApiResponse.error(ApiResponse.FAIL_CODE, ApiResponse.FAIL_MSG); } logger.error("=====Api控制器统一异常处理=====", ex); this.write(response, httpStatus.value(), result); } /** * 描述 http响应: 将{@link ApiResponse}作为返回格式 * * @param response http响应 * @param httpStatus 响应状态 * @param apiResponse 响应对象 * @return * @author *** * @date 2018/11/28 */ private void write(HttpServletResponse response, int httpStatus, ApiResponse apiResponse) { response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); response.setStatus(httpStatus); PrintWriter writer = null; try { writer = response.getWriter(); writer.write(JSON.toJSONString(apiResponse)); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } }
上述:ApiResponse 是自行定义的response响应bean,如下供参考:
package com.jkinfo.api.common.response; import com.fasterxml.jackson.annotation.JsonInclude; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; public class ApiResponse implements Serializable { private static final long serialVersionUID = -507703769787011732L; /** * 成功编码 */ public static final String SUCCESS_CODE = "00"; /** * 成功信息 */ public static final String SUCCESS_MSG = "成功"; /** * 参数缺失编码 */ public static final String FAIL_MISS_PARAM_CODE = "97"; /** * 参数缺失信息 */ public static final String FAIL_MISS_PARAM_MSG = "参数缺失"; /** * 参数类型错误编码 */ public static final String FAIL_MISMATCH_PARAM_TYPE_CODE = "98"; /** * 参数类型错误信息 */ public static final String FAIL_MISMATCH_PARAM_TYPE_MSG = "参数类型错误"; /** * 失败编码 */ public static final String FAIL_CODE = "99"; /** * 失败信息 */ public static final String FAIL_MSG = "系统异常,响应失败"; /** * 请求结果编码 */ private String code; /** * 请求结果信息 */ private String msg; /** * 描述信息 */ @JsonInclude(JsonInclude.Include.NON_NULL) private String description; /** * 业务数据 */ @JsonInclude(JsonInclude.Include.NON_NULL) private Object result; public ApiResponse() { } /** * 调用成功 * * @param t 业务数据 */ public ApiResponse(Object t) { this.code = SUCCESS_CODE; this.msg = SUCCESS_MSG; this.result = t; } /** * 调用失败 * * @param code 错误编码 * @param msg 错误信息 */ public ApiResponse(String code, String msg) { this.code = code; this.msg = msg; } public ApiResponse(String code, String msg, String description) { this.code = code; this.msg = msg; this.description = description; } /** * 是否成功 * * @return true:成功 false:失败 */ public boolean success() { return SUCCESS_CODE.equals(this.getCode()); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } /** * 成功输出 * * @param result 业务数据 * @return String */ public static ApiResponse success(Object result) { ApiResponse success = new ApiResponse(); success.setCode(SUCCESS_CODE); success.setMsg(SUCCESS_MSG); success.setResult(result); return success; } /** * 错误输出 * * @param code * @param msg * @return String */ public static ApiResponse error(String code, String msg) { ApiResponse error = new ApiResponse(); error.setCode(code); error.setMsg(msg); error.setResult(""); return error; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }