我有一个控制器,我想在其中验证不能为空的Path Variable.例如,http://localhost:8080/api/details/expired-timeoff/,其中我想要验证此路径中‘/’后面的PATH变量.

我这里有我的控制器,我想在上面抛出带有错误消息的异常.

@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/datared-timeoff/a"获取时,我可以输入条件并捕获InvalidArgumentException消息 Successfully catch my exception

当我从"http://localhost:8080/api/details/expired-timeoff/",获取信息时,它只会返回默认的白色标签404错误 Exception not catched

我对它做了一些研究,声明Path Variable不能为空,但如果用户不小心将Path变量设置为"空",我该怎么做才能提示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();
    }
}

更新:似乎我可以处理这样的错误.有没有办法让我只使用一个函数来处理所有的问题?try 了String.utils(empNo)和empNo==null,仍然没有进入条件.

// Handles cases where empNo is NOT provided
@GetMapping("/expired-timeoff/")
public List<Details> getExpiredTimeOffBalancesByUser() {
    throw new InvalidArgumentException("Error Message2");
}

推荐答案

您可以这样做:


 @GetMapping({"/expired-timeoff/", "/expired-timeoff/{empNo}"})
 public List<Details> getExpiredTimeOffBalancesByUser(@PathVariable(required=false) String empNo) {
   // test if empNo is null
 }

Java相关问答推荐

ActivityCompat.请求收件箱自动拒绝权限

日食IDE 2024-03在Ubuntu下崩溃,导致hr_err_pid.log

我应该避免在Android中创建类并在运行时编译它们吗?

如何使用解析器组合子解析Java数组类型签名?

当一个链表中间有一个循环时,它的松散部分会发生什么?

缩小画布比例后更改滚动窗格的内部大小

无法在org. openjfx:javafx—fxml:21的下列变体之间进行 Select

Junit with Mockito for java

Java .类参数不通过构造函数传递

如何创建同一类的另一个对象,该对象位于变量中?

相同的Java SerializedLambda为implMethodKind返回不同的结果

Spring-Boot Kafka应用程序到GraalVM本机映像-找不到org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier

在Ubuntu 23.10上使用mp3创建JavaFX MediaPlayer时出错

基于配置switch 的@Controller的条件摄取

EXCEL中的公式单元格显示#NAME?

对从Spring Boot 3.1.5升级到3.2.0的方法的查询验证失败

有没有办法在o(log(N))中以系统的方式将数组中的小块元素复制和移动到新增长的数组中的左侧?

在不使用instanceof或强制转换的情况下从父类变量调用子类方法

java.lang.ClassCastException:com.google.firebase.FirebaseException无法转换为com.google.fire base.auth.FirebaseAuthException

读取ConcurrentHashMap中的可变对象