002-异常处理

Posted bjlhx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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/

 

以上是关于002-异常处理的主要内容,如果未能解决你的问题,请参考以下文章

PCL异常处理:pcl 1.8.13rdpartyoostincludeoost-1_64oost ypeofmsvc ypeof_impl.hpp(125): error(代码片段

使用片段中的处理程序时出现非法状态异常

Java异常处理机制

HLS NGINX-RTMP [错误] 1281#0:* 58 hls:强制片段拆分:10.002 秒

java 反射代码片段

java.util.MissingResourceException: Can't find bundle for base name init, locale zh_CN问题的处理(代码片段