Skip to content

Spring Boot 参数类型错误 rest 提示 #47

Open
@Shellbye

Description

@Shellbye

在上一篇文章 #46 中,介绍了一种当必填参数没有传入时的比较友好的提示方式,今天在顺着同样的思路,介绍另外一种情况:参数类型错误时的处理情况。

问题描述

当你使用Spring Boot时,如果接口的输入参数有误,后端的默认提示是这个样子的:

a

是不是一种不知所措的感觉呢?相比与上一篇的默认提示,这个提示简直就是太不友好了,我们想要的其实是这个样子的:

b

解决方案

与上一篇的思路简直是如出一辙,依然是找到那个正确的异常(TypeMismatchException),然后对它进行一些相应的处理就好。

项目目录结构

c

关键代码
Controller.java

package com.example.demo;

import org.springframework.web.bind.annotation.*;


@RestController
public class Controller {
    @RequestMapping(value = "/demo", method = RequestMethod.GET)
    public @ResponseBody
    String demo(@RequestParam(value = "p1") Integer p1) {
        return "OK";
    }
}

TypeMismatchExceptionHandler.java

package com.example.demo;

import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


@ControllerAdvice
public class TypeMismatchExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleTypeMismatch(
            TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String msg = String.format("{\"code\":\"400202\",\"data\":{},\"message\":\"参数%s类型错误,要求是%s\"}\n",
                ((MethodArgumentTypeMismatchException) ex).getName(), ex.getRequiredType());
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions