Springboot:PathVariable 验证,其中条件 {variable}.isBlank/{variable}.isEmpty 不起作用

问题描述 投票:0回答:1

我有一个控制器,我想验证 PathVariable 不能为空。例如,http://localhost:8080/api/details/expired-timeoff/ 我想验证此路径中“/”后面的路径变量。

我的控制器在这里,我想在其中抛出带有错误消息的异常。

@RestController
@CrossOrigin("*")
@RequestMapping("/api/details")
public class DetailsController {
    @Autowired
    DetailsService detailsService;
    
    @Autowired
    OvertimeService overtimeService;
        
    // TESTING HERE!!!!
    @GetMapping("/expired-timeoff/{empNo}")
    public List<Details> getExpiredTimeOffBalancesByUser(@PathVariable String empNo) {

        if (empNo.isBlank() || empNo.isEmpty() || empNo.trim().equals("a")) {
            throw new InvalidArgumentException("Error Message");
        }
        return detailsService.findExpiredTimeOffBalancesByCreatedBy(empNo);
    }


}

同时,当我从“http://localhost:8080/api/details/expired-timeoff/a”获取时,我可以输入条件并捕获我的 InvalidArgumentException 消息 Successfully catch my exception

当我从“http://localhost:8080/api/details/expired-timeoff/”获取时,它只会返回默认的 Whitelabel 404 错误 Exception not catched

我研究了一下,据说PathVariable不能为null,但是如果用户不小心把path变量设置为null,怎么办才能提示InvalidArgumentException呢?

这是我的@RestControllerAdvise 文件

package com.sicmsb.timeofftracker.controller.Advice;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;

import com.sicmsb.timeofftracker.exceptions.ResourceNotFoundException;
import com.sicmsb.timeofftracker.exceptions.InvalidArgumentException;

@RestControllerAdvice
public class RequestExceptionHandler {
    @ResponseStatus(HttpStatus.NOT_FOUND) //404
    @ExceptionHandler(ResourceNotFoundException.class)
    public String notFound(Exception e) {
        //e.printStackTrace();
        return e.getMessage();
    }
    
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //500
    @ExceptionHandler({RuntimeException.class, Exception.class})
    public String internalError(Exception e) {
        e.printStackTrace();
        return "error/internal_error";
    }
    
    @ResponseStatus(HttpStatus.BAD_REQUEST) //400
    @ExceptionHandler({InvalidArgumentException.class})
    public String badRequest(Exception e) {
        return e.getMessage();
    }
}

java spring-boot spring-mvc
1个回答
0
投票

尝试在 IF 语句中添加一个条件来检查 empNo 是否为空。

       if (empNo==null || empNo.isBlank() || empNo.isEmpty() || empNo.trim().equals("a")) { throw new InvalidArgumentException("Error Message"); }

© www.soinside.com 2019 - 2024. All rights reserved.