Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 393|回复: 0

springmvc请求参数异常统一处理

[复制链接]
  • TA的每日心情
    奋斗
    前天 12:19
  • 签到天数: 785 天

    [LV.10]以坛为家III

    2049

    主题

    2107

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    721632
    发表于 2021-5-26 14:44:42 | 显示全部楼层 |阅读模式

     1、ExceptionHandlerController

    package com.oy.controller;
    
    import java.text.MessageFormat;
    
    import org.springframework.beans.TypeMismatchException;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.converter.HttpMessageNotReadableException;
    import org.springframework.web.HttpRequestMethodNotSupportedException;
    import org.springframework.web.bind.MissingServletRequestParameterException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
    
    import com.alibaba.fastjson.JSONObject;
    
    import com.oy.exception.ForbiddenException;
    import com.oy.utils.UtilFunctions;
    
    @ControllerAdvice
    public class ExceptionHandlerController {
    
        @ExceptionHandler(RuntimeException.class)
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ResponseBody
        public JSONObject runtimeExceptionHandler(RuntimeException ex) {
            UtilFunctions.log.error("runtimeExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            response.put("message", "Internal Server Error");
            return response;
        }
    
        @ExceptionHandler(NullPointerException.class)
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ResponseBody
        public JSONObject nullPointerExceptionHandler(NullPointerException ex) {
            UtilFunctions.log.error("nullPointerExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            response.put("message", "Internal Server Error");
            return response;
        }
    
        /*----- REQUEST ERROR -----*/
        @ExceptionHandler({ ForbiddenException.class })
        @ResponseStatus(HttpStatus.FORBIDDEN)
        @ResponseBody
        public JSONObject requestForbidden(ForbiddenException ex) {
            UtilFunctions.log.error("ForbiddenExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            response.put("message", ex.getMessage());
            return response;
        }
    
        @ExceptionHandler({ TypeMismatchException.class })
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public JSONObject requestTypeMismatch(TypeMismatchException ex) {
            UtilFunctions.log.error("TypeMismatchExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            // response.put("message", "Bad Request");
            // response.put("message", "Bad Request,  parameter type of " + ex.getPropertyName() + " need be " + ex.getRequiredType());
            
            if (Double.class.equals(ex.getRequiredType()) ||  Integer.class.equals(ex.getRequiredType())) {
                response.put("message", "Bad Request, " +  ex.getValue() + " not a number");
            } else {
                String strTemplate = "Bad Request, {0} is invalid, a type of {1} is needed";
                response.put("message", MessageFormat.format(strTemplate, ex.getValue(), ex.getRequiredType().getName()));
            }
            return response;
        }
    
        @ExceptionHandler({ MissingServletRequestParameterException.class })
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public JSONObject requestMissingServletRequest(MissingServletRequestParameterException ex) {
            UtilFunctions.log.error("MissingServletRequestParameterExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            // response.put("message", "Bad Request");
            String strTemplate = "Bad Request, param:{0} is required, type:{1}";
            response.put("message", MessageFormat.format(strTemplate, ex.getParameterName(), ex.getParameterType()));
            return response;
        }
        
        @ExceptionHandler({ NoSuchRequestHandlingMethodException.class })
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public JSONObject NoSuchRequestHandlingMethodExceptionHandler(NoSuchRequestHandlingMethodException ex) {
            UtilFunctions.log.error("NoSuchRequestHandlingMethodExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            response.put("message", "Not Found");
            return response;
        }
        
        /*----- REQUEST ERROR -----*/
        @ExceptionHandler({ HttpMessageNotReadableException.class })
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public JSONObject requestNotReadable(HttpMessageNotReadableException ex) {
            UtilFunctions.log.error("HttpMessageNotReadableExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            response.put("message", "Bad Request");
            return response;
        }
    
        @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
        @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
        @ResponseBody
        public JSONObject request405(HttpRequestMethodNotSupportedException ex) {
            UtilFunctions.log.error("HttpRequestMethodNotSupportedExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
            JSONObject response = new JSONObject();
            // response.put("message", "Method Not Allowed");
            response.put("message", ex.getMessage());
            return response;
        }
    }

     

    2、postman测试

     

    3、异常增强类型:

      NullPointerException,RunTimeException,ClassCastException,

      NoSuchMethodException,IOException,IndexOutOfBoundsException


      以及springmvc自定义异常等,如下:

        SpringMVC自定义异常 对应的status code 
               Exception                       HTTP Status Code  
    ConversionNotSupportedException         500 (Internal Server Error)
    HttpMessageNotWritableException         500 (Internal Server Error)
    HttpMediaTypeNotSupportedException      415 (Unsupported Media Type)
    HttpMediaTypeNotAcceptableException     406 (Not Acceptable)
    HttpRequestMethodNotSupportedException  405 (Method Not Allowed)
    NoSuchRequestHandlingMethodException    404 (Not Found) 
    TypeMismatchException                   400 (Bad Request)
    HttpMessageNotReadableException         400 (Bad Request)
    MissingServletRequestParameterException 400 (Bad Request)

    参考资料:

      (1)springmvc通过异常增强返回给客户端统一格式

      (2)springmvc请求参数异常处理

      (3)@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

      (4)https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-8-27 09:29 , Processed in 0.093690 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表