简体   繁体   中英

Quarkus or Javax Response with not type

One thing i hate of Quarkus is that when you try manage your Response HTTP like ResponseEntity the type of Response are lost and you can define the type you return for avoid developement error. ¿There is a way to define the type and return a code error when you like?

Something like this code, i like can choose the type of Response and also choose the status i like.

@POST
@Path("/{storeCode}/schedules")
public Response createHolidaySchedule(@PathParam("storeCode") String storeCode, @QueryParam("day") String day) {
    try {
        HolidaySchedule response = new HolidaySchedule();
        return Response.ok(response).build();
    } catch (Exception e) {
        return Response.status(500).build();
    }
}

That's give me and idea, we can use the ExceptionHandler and Build the response Status using a Controller exception, it's create using JAX-RS status or whatever your want.

@Provider
public class ControllerExceptionHandler implements ExceptionMapper<ControllerException> 
{
    @Override
    public Response toResponse(ControllerException exception) 
    {
        return ControllerException.toResponse(exception);  
    }
}

For you can catch the exception you must be throw first and before you need created, something like that:

@POST
@Path("/{storeCode}/schedules")
public HolidaySchedule createHolidaySchedule(@PathParam("storeCode") String storeCode, @QueryParam("day") String day) throws ControllerException {
    try {
        HolidaySchedule response = new HolidaySchedule();
        return response;
    } catch (Exception e) {
        ErrorMessage msg = ErrorMessage.from("Ups not work");
        throw new ControllerException(Status.BAD_REQUEST, msg);
    }
}

The ControllerException has a two static functions which create a JAX-RS Response or a Builder for other modifications like content-type or something more.

public class ControllerException extends Exception {

    private static final long serialVersionUID = 1L;
    private Status status;
    private Object body;

    public ControllerException(Status status, Object body) {
        this.status = status;
        this.body = body;
    }
    
    public ControllerException(Status status) {
        this(status, null);
    }
    
    public static Response toResponse(ControllerException exception) {
        return ControllerException.toResponseBuilder(exception).build();
    }
    
    public static ResponseBuilder toResponseBuilder(ControllerException exception) {
        return Response.status(exception.status).entity(exception);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM