zoukankan      html  css  js  c++  java
  • Spring 微服务开放api 抛出HttpStatus @ResponseStatus的妙用

     在团队项目开发中经常需要与各种语言的其他系统交互,开发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();
            }
        }
    
    }


    -- 沉着,冷静,bug总会解决,未来道路很光明。
  • 相关阅读:
    Linux系统编程之--守护进程的创建和详解【转】
    【转】Android虚拟平台的编译和整合
    【转】6.4.6 将驱动编译进Linux内核进行测试
    【转】Linux驱动模块编译进内核中
    【转】Android HAL实例解析
    【转】ubuntu下解压缩zip,tar,tar.gz和tar.bz2文件
    【转】Linux下tar.xz结尾的文件的解压方法--不错
    【转】linux tree命令以树形结构显示文件目录结构 ---- 不错
    【转】NDK编译可执行文件在Android L中运行显示error: only position independent executables (PIE) are supported.失败问题解决办法。------不错
    【转】Notepad++ 快捷键 大全 官方整理过来的
  • 原文地址:https://www.cnblogs.com/dadadajiong/p/15131930.html
Copyright © 2011-2022 走看看