簡體   English   中英

Spring Boot 應用程序中的自定義異常拋出

[英]Custom Exception throw in Spring Boot Application

我想使用@ControllerAdvice@ExceptionHandler在我的 spring boot 應用程序中創建一些自定義異常,但我可以將異常詳細信息作為 json

我嘗試了一切都找不到解決方案。 ErrorDetails是我使用 setter 和 getter 的類,而StringNotFoundException是擴展 Exception 的類

    @ControllerAdvice()
    public class RestExceptionHandler {

    @Autowired
    Environment environment;

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ExceptionHandler(StringNotFoundException.class)
    @ResponseBody
    public ErrorDetails handleNotFoundException(StringNotFoundException ex, HttpServletRequest request) {

        ErrorDetails ed = new ErrorDetails();
        ed.setErrorCode("10000");
        ed.setErrorMessage(ex.getMessage());
        ed.setErrorDescription("Try");
        ed.setPort(environment.getProperty("local.server.port"));
        ed.setUrl(request.getRequestURI().toString());
        System.out.println(ed + "****************");
        return ed;}}

在控制器中我使用這個:

if (companyList.isEmpty()) {
throw new StringNotFoundException();
            }

異常詳細信息顯示在控制台上,但我無法獲取 json 格式

com.ffi.financialcompany.exception.StringNotFoundException

嘗試讓 RestExceptionHandler 擴展 ResponseEntityExceptionHandler。

ResponseEntityExceptionHandler 是 Spring 框架用來拋出異常的類。 我認為您應該擴展該課程以解決此問題。

    @ControllerAdvice()
    public class RestExceptionHandler extends  ResponseEntityExceptionHandler {
    ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM