Spring Boot 如何处理扔

gk7wooem  于 2023-01-05  发布在  Spring
关注(0)|答案(3)|浏览(114)

我做了一个像sample这样的项目。控制器是这样的

package mypackagename.controller;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
@RequestMapping("/")
public class StoresRestController {

    @RequestMapping(method = RequestMethod.GET)
    public String stores() {
        return ...
    }

}

我喜欢处理所有的throwables,并作出我的定制统一的响应。问题是我找不到一个指南或样本来正确地做到这一点。
首先,我尝试了ExceptionHandlerThrowable,但是没有效果,所以我决定继续。然后,我发现最接近的方法是this,所以我尝试了jersey,添加了类似this的东西。但是它并不是对所有的throwables都有效。而且,它会通过抱怨忽略我的控制器

o.g.jersey.internal.inject.Providers     : A provider mypackagename.controller.StoresRestController registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider mypackagename.controller.StoresRestController will be ignored.

我搜索了这个错误,发现了this,我没有在我的项目中使用ContainerResponseFilter,因为我提供了上面的例子。所以我一无所知。主要的问题是如何处理所有的throwables,但如果你能给予我一些关于如何解决Providers问题的建议,我将非常感激。

nhaq1z21

nhaq1z211#

在我的项目中,我使用@ControllerAdvice来处理我的异常。这里有一个例子。希望这能有所帮助。只要确保这个类在你的组件扫描中,这样它就能被选中。

@RestController
@ControllerAdvice
public class StoresExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public ResponseEntity<Object> handleThrowable(final Throwable ex) {
        return new ResponseEntity<Object>("Unable to process request.", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
avkwfej4

avkwfej42#

最后this post帮助我处理了所有的Throwable,除了验证异常。重要的部分是使用@EnableWebMvcResponseEntityExceptionHandler。为了处理验证异常,我使用了this answer。希望它能帮助到一些人。

mrphzbgm

mrphzbgm3#

正如@carlos-cook所说,您可以使用RFC 7807中定义的@ControllerAdviceProblemDetail,如下所示:

import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(RuntimeException.class)
  public ProblemDetail handleUnexpectedException(RuntimeException rte, WebRequest wr) {
        ProblemDetail pd = this.createProblemDetail(HttpStatus.INTERNAL_SERVER_ERROR, rte);
        pd.setType(URI.create("http://your-site.com/internal-server-error"));
        pd.setTitle("Internal server error");
        return pd;
    }

  @ExceptionHandler(YourCustomeException.class)
  public ProblemDetail handleUnexpectedException(YourCustomException rte, WebRequest wr) {
        ProblemDetail pd = this.createProblemDetail(HttpStatus.INTERNAL_SERVER_ERROR, rte);
        pd.setType(URI.create("http://your-site.com/custom-error-page"));
        pd.setTitle("Internal server error");
        return pd;
    }
}

然后在控制器中,您可以简单地抛出YourCustomException
这个控制器通知将分别处理每个异常和YourCustomException。

相关问题