• 002-异常处理


    一、概述

      在spring 体系中,异常处理有如下:https://www.cnblogs.com/bjlhx/p/8666653.html

      可以结合jsr303使用:https://www.cnblogs.com/bjlhx/p/10305344.html

    二、请求参数类异常

      结合以上两种以及上文api设计原则修改响应数据,将请求参数类异常定位到http响应吗为4XX类,如下

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
    
        @ExceptionHandler(value = ConstraintViolationException.class)
        @ResponseBody
        public ResponseEntity constraintViolationExceptionHandler(Exception e) {
            Map<String,Object> result=new HashMap();
            result.put("code",400);
            result.put("msg",e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
    
        @ExceptionHandler(value = javax.validation.UnexpectedTypeException.class)
        @ResponseBody
        public ResponseEntity unexpectedTypeExceptionHandler(Exception e) {
            Map<String,Object> result=new HashMap();
            result.put("code",400);
            result.put("msg",e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
    
        @ExceptionHandler(value = org.springframework.http.converter.HttpMessageNotReadableException.class)
        @ResponseBody
        public ResponseEntity httpMessageNotReadableExceptionHandler(Exception e) {
            Map<String,Object> result=new HashMap();
            result.put("code",400);
            result.put("msg","没有请求体,详细:"+e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
    
    
        @ExceptionHandler(value = org.springframework.web.bind.MethodArgumentNotValidException.class)
        @ResponseBody
        public ResponseEntity methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
            Map<String,Object> result=new HashMap();
            result.put("code",400);
            result.put("msg","请求体校验失败,详细:"+e.getMessage());
            if (e.getBindingResult().hasErrors()) {
                List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
                result.put("data",fieldErrors);
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
        @ExceptionHandler(value = Exception.class)
        public void errorHandler(Exception e,HttpServletResponse response) throws IOException {
            response.sendError(HttpStatus.BAD_REQUEST.value());
        }
    }

    可以参看:https://blog.jayway.com/2014/10/19/spring-boot-error-responses/

  • 相关阅读:
    pathon学习总结(二)pathon的基础语法
    python学习总结(一),第一个python程序的编写
    数组中查找最大值和最小值 (两种方法)
    websocket----聊天室,推送等服务
    django-celery 应用方法
    vue-resource
    Vue-router
    vue 属性绑定
    Vue的生命周期以及钩子函数
    安装 vue 及 组件
  • 原文地址:https://www.cnblogs.com/bjlhx/p/10329369.html
Copyright © 2020-2023  润新知