相关疑难解决方法(0)

Spring boot 404错误自定义错误响应ReST

我正在使用Spring启动来托管REST API.我希望始终发送JSON响应,而不是标准的错误响应,即使浏览器正在访问URL以及自定义数据结构.

我可以使用@ControllerAdvice和@ExceptionHandler来实现自定义异常.但我无法找到任何好的方法来处理标准和处理错误,如404和401.

有没有什么好的模式如何做到这一点?

java rest spring json spring-boot

11
推荐指数
6
解决办法
2万
查看次数

如何处理Spring Boot重定向到/ error?

我遇到了与这个问题相同的问题,使用Spring Boot 1.3.0而没有我的控制器注释@RestController,只是@Path@Service.正如该问题中的OP所说,

对我来说,这不是明智的事

我也无法理解他们为什么会将它重定向到/ error.我很可能会遗漏一些东西,因为我只能向客户回馈404或200.

我的问题是他的解决方案似乎不适用于1.3.0,所以我有以下请求流:让我们说我的代码抛出一个NullPointerException.它将由我ExceptionMapper的一个人处理

@Provider
public class GeneralExceptionMapper implements ExceptionMapper<Throwable> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GeneralExceptionMapper.class);

    @Override
    public Response toResponse(Throwable exception) {
        LOGGER.error(exception.getLocalizedMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的代码返回500,但不是将其发送回客户端,而是尝试将其重定向到/ error.如果我没有其他资源,它将发回404.

2015-12-16 18:33:21.268  INFO 9708 --- [nio-8080-exec-1] o.glassfish.jersey.filter.LoggingFilter  : 1 * Server has received a request on thread http-nio-8080-exec-1
1 > GET http://localhost:8080/nullpointerexception
1 > accept: */*
1 > host: localhost:8080
1 > …
Run Code Online (Sandbox Code Playgroud)

java jax-rs jersey jersey-2.0 spring-boot

7
推荐指数
1
解决办法
2826
查看次数

Spring Boot @ControllerAdvice异常处理程序没有触发

我设置了以下控制器建议,以返回错误条件的API合同:

@ControllerAdvice
public class ExceptionHandler : ResponseEntityExceptionHandler()
{
    @ExceptionHandler(Throwable::class)
    @ResponseBody
    public fun onException(ex: Throwable): ResponseEntity<ErrorResponse>
    {
        val errorResponse = ErrorResponse(
           response = ResponseHeader(ex.responseCode(), ex.message))
        return ResponseEntity(errorResponse, HttpStatus.UNAUTHORIZED);
    }

}
Run Code Online (Sandbox Code Playgroud)

工作的罚款,然后停止工作.现在所有异常都被路由到BasicErrorController,返回以下格式:

{
  "timestamp" : 1450495303166,
  "status" : 403,
  "error" : "Forbidden",
  "message" : "Access Denied",
  "path" : "/profile/candidates"
}
Run Code Online (Sandbox Code Playgroud)

以上是一个很好的自以为是的起点,但现在它不会让步.

  • 我尝试用一​​个ExceptionHandlerExceptionResolver但是没有用的实例替换错误处理程序.
  • 我已经尝试制作自己的CustomErrorHandler,但这也不合适,因为在HttpServletRequest重新路由到自定义错误控制器时,原始异常不再存在.需要此信息才能向客户端返回适当的响应.

我怎么样:

  • 使SpringBoot 向异常控制器转发异常.
  • 恢复@ControllerAdvice异常处理程序,这样我就可以返回一个合适的响应体和状态代码.

在启动弹簧日志:

main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in exceptionHandler
main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc kotlin spring-boot

7
推荐指数
1
解决办法
3950
查看次数

spring boot覆盖默认的REST异常处理程序

我无法在REST api中覆盖默认的Spring引导错误响应.我有以下代码

@ControllerAdvice
@Controller
class ExceptionHandlerCtrl {

    @ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Invalid data")
    @ExceptionHandler(BusinessValidationException.class)
    @ResponseBody
    public ResponseEntity<BusinessValidationErrorVO> handleBusinessValidationException(BusinessValidationException exception){
        BusinessValidationErrorVO vo = new BusinessValidationErrorVO()
        vo.errors = exception.validationException
        vo.msg = exception.message
        def result =  new ResponseEntity<>(vo, HttpStatus.UNPROCESSABLE_ENTITY);
        result

    }
Run Code Online (Sandbox Code Playgroud)

然后在我的REST api中,我抛出了这个BusinessValidationException.调用此处理程序(我可以在调试器中看到它)但是我仍然有默认的spring boot REST错误消息.有没有办法覆盖并使用默认值作为后备?带有常规的Spring Boot版本1.3.2.最好的祝福

rest groovy spring spring-boot

6
推荐指数
1
解决办法
6699
查看次数

spring rest处理空请求体(400 Bad Request)

我正在使用Spring4开发RESTful应用程序.我想在POST请求中没有传递正文时处理大小写.我写自定义异常处理程序:

@ControllerAdvice
public class MyRestExceptionHandler {

  @ExceptionHandler
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ResponseEntity<MyErrorResponse> handleJsonMappingException(JsonMappingException ex) {
      MyErrorResponse errorResponse = new MyErrorResponse("request has empty body");
      return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
  }   
  @ExceptionHandler(Throwable.class)
  public ResponseEntity<MyErrorResponse> handleDefaultException(Throwable ex) {
    MyErrorResponse errorResponse = new MyErrorResponse(ex);
    return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
  }

}
 @RestController
 public class ContactRestController{
    @RequestMapping(path="/contact", method=RequestMethod.POST)
    public void save(@RequestBody ContactDTO contactDto) {...}
 } 
Run Code Online (Sandbox Code Playgroud)

但是当它发生时,这些方法将不会被调用.我刚收到400 BAD REQUEST http状态和空身的响应.有人知道如何处理吗?

java rest spring spring-boot spring-4

6
推荐指数
2
解决办法
1万
查看次数

Spring Error Controller响应,不可接受

我已经构建了一个错误控制器,它应该是我在Spring REST服务中捕获异常的"最后一行".但是,我似乎无法将POJO作为响应类型返回.为什么杰克逊不为这个案子工作?

我的班级看起来像:

@RestController
public class CustomErrorController implements ErrorController
{
  private static final String PATH = "/error";

  @Override
  public String getErrorPath()
  {
     return PATH;
  }


  @RequestMapping (value = PATH)
  public ResponseEntity<WebErrorResponse> handleError(HttpStatus status, HttpServletRequest request)
  {
     WebErrorResponse response = new WebErrorResponse();

    // original requested URI
    String uri = String.valueOf(request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI));
    // status code
    String code = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE));
    // status message
    String msg = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_MESSAGE));

    response.title = "Internal Server Error";
    response.type = request.getMethod() + ": " + uri;
    response.code = Integer.valueOf(code);
    response.message …
Run Code Online (Sandbox Code Playgroud)

java rest spring spring-boot

5
推荐指数
1
解决办法
8683
查看次数

Kotlin + Spring Boot请求编组

鉴于以下有效负载:

data public class CandidateDetailDTO(val id: String,
                                     val stageName: String,
                                     val artists: Iterable<ArtistDTO>,
                                     val instruments: Iterable<InstrumentDTO>,
                                     val genres: Iterable<GenreDTO>,
                                     val discoverable: Boolean,
                                     val gender: Gender,
                                     val involvement: Involvement,
                                     val biography: String,
                                     var photoURLs: List<URL>,
                                     var birthday: Date? = null,
                                     var customGenre: String? = null)
Run Code Online (Sandbox Code Playgroud)

..如图所示,某些字段允许为空,其他字段不允许.

使用Spring Boot调用请求时,如果缺少预期字段,则返回400 - Bad Request.这是不太令人期待的,我期望相关的控制器建议适用:

@ControllerAdvice
public class SomeExceptionHandler : ResponseEntityExceptionHandler()
{
    @ExceptionHandler(Throwable::class)
    @ResponseBody
    public fun onException(ex: Throwable): ResponseEntity<ErrorResponse>
    {
        val responseCode = ex.responseCode()
        val errorResponse = ErrorResponse(response = ResponseHeader(responseCode, ex.message))
        return ResponseEntity(errorResponse, responseCode.httpStatus());
    } …
Run Code Online (Sandbox Code Playgroud)

java spring jackson kotlin spring-boot

3
推荐指数
1
解决办法
4302
查看次数