我有一个控制器,我想在其中验证不能为空的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");
}