zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    ES6学习--函数剩余参数 (rest参数)
    ES6学习 --函数参数默认值与解构赋值默认值
    ES6学习--Array.from()方法
    02ython基础知识(一)
    01 Python初探
    c#利用IronPython调用python的过程种种问题
    Android 对话框(Dialogs)
    不可不知的安卓屏幕知识
    C#中的Split用法以及详解
    关于XML文档操作类
  • 原文地址:https://www.cnblogs.com/bjlhx/p/10329369.html
Copyright © 2011-2022 走看看