Quarkus 异常处理程序

tcs*_*dev 5 quarkus

quarkus 是否提供异常处理程序?

我想要像 Spring 的 ControllerAdvice 这样的东西。

https://www.baeldung.com/exception-handling-for-rest-with-spring

Gui*_*met 17

Quarkus/RESTEasy 世界中的等价物称为ExceptionMapper.

例如,请参见此处:https : //howtodoinjava.com/resteasy/resteasy-exceptionmapper-example/


Sib*_*med 10

我们可以使用ExceptionMapper来处理自定义异常。

javax.ws.rs.ext.ExceptionMapper
Run Code Online (Sandbox Code Playgroud)

接口 ExceptionMapper<E extends Throwable>为将 Java 异常 E 映射到 Response 的提供者定义了一个契约。

这是一个简单的示例,Quarkus REST API 中的自定义异常处理

自定义异常

import java.io.Serializable;

public class CustomException extends
        RuntimeException implements Serializable {

    private static final long serialVersionUID = 1L;

    public CustomException() {
    }

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomException(Throwable cause) {
        super(cause);
    }

    public CustomException(String message, Throwable cause, 
                           boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误信息

package org.knf.dev.demo.exception;

public class ErrorMessage {

    private String message;
    private Boolean status;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public ErrorMessage(String message, Boolean status) {
        super();
        this.message = message;
        this.status = status;
    }

    public ErrorMessage() {
        super();
    }

}
Run Code Online (Sandbox Code Playgroud)

自定义异常处理程序

package org.knf.dev.demo.exception;

import org.eclipse.microprofile.config.inject.ConfigProperty;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class CustomExceptionHandler implements ExceptionMapper<CustomException> {

    @ConfigProperty(name = "knowledgefactory.custom.error.msg.usernotfound")
    String userNotFound;

    @Override
    public Response toResponse(CustomException e) {

        if (e.getMessage().equalsIgnoreCase(userNotFound)) {
            return Response.status(Response.Status.NOT_FOUND).
                    entity(new ErrorMessage(e.getMessage(), false)).build();
        } else {

            return Response.status(Response.Status.BAD_REQUEST).
                    entity(new ErrorMessage(e.getMessage(), false)).build();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Quarkus 端点:

import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.knf.dev.demo.data.User;
import org.knf.dev.demo.data.UserData;
import org.knf.dev.demo.exception.CustomException;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/api/v1")
public class UserController {

    @ConfigProperty(name = "knowledgefactory.custom.error.msg.badrequest.numeric")
    String idNumericErrorMsg;

    @ConfigProperty(name = "knowledgefactory.custom.error.msg.usernotfound")
    String userNotFound;

    @Inject
    UserData userData;

    @GET
    @Path("/users/{id}")
    public Response findUserById(@PathParam("id") String id)
            throws CustomException {
        Long user_id = null;
        try {
            user_id = Long.parseLong(id);
        } catch (NumberFormatException e) {
            throw new CustomException(idNumericErrorMsg);
        }
        User user = userData.getUserById(user_id);
        if (user == null) {
            throw new CustomException(userNotFound);
        }
        return Response.ok().entity(userData.getUserById(user_id)).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

无效请求(未找到用户 ID): 在此输入图像描述

无效请求(用户 ID 必须是数字): 在此输入图像描述

有效请求: 在此输入图像描述