Spring Boot应用程序中的自定义异常抛出

时间:2019-04-30 19:23:32

标签: java

我想使用@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

1 个答案:

答案 0 :(得分:0)

尝试使RestExceptionHandler扩展ResponseEntityExceptionHandler。

ResponseEntityExceptionHandler是Spring框架用于引发Exception的类。我认为您应该扩展该类以便解决此问题。

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