在团队项目开发中经常需要与各种语言的其他系统交互,开发api接口的时候除了接口风格遵循restFul风格,HTTP STATUS 的响应头更能帮助区分接口调用状态。
Spring微服务项目中在controller中 可以用注解的方式 @ResponseStatus 。
@ResponseStatus @PostMapping("/update") public HttpApiResponse<String> update(@RequestBody SysCompanyUpdateReq company){ try { return companyService.update(company); } catch (ApiInvokingException e) { e.printStackTrace(); return HttpApiResponse.fail("修改失败:"+e.getMessage()); } }
如果需要自定义某些错误,并希望能反馈HTTP STATUS ,可以对项目全局做自定义异常捕获, 针对Controller ,可以使用注解@ControllerAdvice @ExceptionHandler
对一些自定义异常做处理
例如创建一个异常类 ApiInvokingException
@NoArgsConstructor public class ApiInvokingException extends Exception { public ApiInvokingException(String message) { super(message); } }
定义一个公共异常类 ,系统出错的时候 handleException 能够捕获错误,
@ControllerAdvice public class GlobalExceptionHandler { @ResponseStatus(org.springframework.http.HttpStatus.NOT_FOUND) @ResponseBody @ExceptionHandler(ApiInvokingException.class) public Object handleException(ApiInvokingException e) { String msg = e.getMessage(); if (msg == null || msg.equals("")) { msg = "连接第三方api失败"; } // 不允许访问 JSONObject jsonObject = new JSONObject(); jsonObject.put("resultMessage", msg); jsonObject.put("result", ""); jsonObject.put("resultCode", org.springframework.http.HttpStatus.NOT_FOUND); jsonObject.put("success", false); return jsonObject; } @ResponseStatus(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody @ExceptionHandler(Exception.class) public Object handleException(Exception e) { String msg = e.getMessage(); if (msg == null || msg.equals("")) { msg = "服务器出错,请联系管理员"; } // 不允许访问 JSONObject jsonObject = new JSONObject(); jsonObject.put("resultMessage", msg); jsonObject.put("result", ""); jsonObject.put("resultCode", org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR); jsonObject.put("success", false); return jsonObject; } }
以上针对Controller,如果是过滤器Filter异常处理并且要返回HTTP STATUS ,如果是能判断的错误,可以直接简单粗暴的修改response的状态码
public class JwtAuthenticationFilter extends BasicAuthenticationFilter { @Autowired public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // 获取token, 并检查登录状态 try { SecurityUtils.checkAuthentication(request); chain.doFilter(request, response); }catch (JwtValException e){ response.setContentType("application/json; charset=utf-8"); //直接定义response 状态码 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); String json = JSONObject.toJSONString(HttpApiResponse.fail(e.getErrorEnum().getCode(),e.getErrorEnum().getMessage())); response.getWriter().print(json); response.getWriter().flush(); response.getWriter().close(); } } }