当类型为 Long 且客户端发送字符串(不是数字)时,在 @PathVariable 中捕获强制转换异常 [英] Catch cast exception in @PathVariable when type is Long and Client sent String(not number)

查看:12
本文介绍了当类型为 Long 且客户端发送字符串(不是数字)时,在 @PathVariable 中捕获强制转换异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有参数 @PathVariable long stopPointId 的 Spring Boot 控制器,当用户将发送像url/StopPoints/1"这样的请求时一切正常,但是当请求看起来像url/StopPoints/StopPointNumber"时;什么都不会发生.我想抓住这种情况并抛出我的自定义错误,因为用户需要知道,该参数只需要很长的值.例如:您不能将 String 作为参数传递.您应该使用数字值,例如 123."

I have a Spring Boot controller with param @PathVariable long stopPointId, when user will be send request like "url/StopPoints/1" everything work perfect, but when request will be look like "url/StopPoints/StopPointNumber" nothing will be happening. I want to catch this situation and throw my custom error because user need to know, that param only take long value. For instance: You are not able to pass String as parameter. You should use number value e.g 123."

推荐答案

一种方法是处理 NumberFormatException,Spring Boot 在尝试将 String 类型转换为 Long 时会抛出该异常.

One way would be to handle the NumberFormatException that would be thrown by Spring Boot while trying to typecast a String into a Long.

这是我自定义的 HTTP-Response 类,但我相信您有自己的...

This is my custom HTTP-Response class, but I trust you have your own...

package com.stackoverflow.rav.StackOverflowExamples.api;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.http.HttpStatus;

import java.util.Date;

public class HttpResponse {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-dd-yyyy hh:mm:ss", timezone = "UTC")
    private Date timeStampUTC;
    private int httpStatusCode;
    private HttpStatus httpStatus;
    private String reason;
    private String message;
    
    /* Include setters, getters, constructors, or use Lombok */

}

然后是异常处理程序...(异常消息应该是通用的,以增加可重用性)

Then the exception handler... (exception message should be generic in order to increase reusability)

package com.stackoverflow.rav.StackOverflowExamples.api;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExampleExceptionHandler {

    @ExceptionHandler(NumberFormatException.class)
    public ResponseEntity<HttpResponse> accountDisabledException() {
        return createHttpResponse(HttpStatus.BAD_REQUEST, "Should pass long not string!");
    }

    private ResponseEntity<HttpResponse> createHttpResponse(HttpStatus httpStatus, String message) {
        return new ResponseEntity<>(new HttpResponse(
                httpStatus.value(),
                httpStatus,
                httpStatus.getReasonPhrase().toUpperCase(),
                message.toUpperCase()),
                httpStatus);
    }
}

最后是控制器...

package com.stackoverflow.rav.StackOverflowExamples.api;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController extends ExampleExceptionHandler {

    @GetMapping("/url/{someValue}")
    public String hello(@PathVariable("someValue") long someValue) {

        return "You entered: " +someValue;
    }
}

如果一切顺利,您应该在执行 http://localhost:8080/url/abcd 时得到如下屏幕片段的响应

If all goes well you should get a response like the screen-snippet below when doing http://localhost:8080/url/abcd

这个答案可能看起来很长,但我们是 Java 开发人员 :D

This answer might look lengthy, but we are Java developers :D

这篇关于当类型为 Long 且客户端发送字符串(不是数字)时,在 @PathVariable 中捕获强制转换异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆