|
| 1 | +package com.flit.runtime.jaxrs; |
| 2 | + |
| 3 | +import com.flit.runtime.FlitException; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | +import javax.servlet.http.HttpServletRequest; |
| 7 | +import javax.ws.rs.core.Context; |
| 8 | +import javax.ws.rs.core.MediaType; |
| 9 | +import javax.ws.rs.core.Response; |
| 10 | +import javax.ws.rs.ext.ExceptionMapper; |
| 11 | +import org.slf4j.Logger; |
| 12 | +import org.slf4j.LoggerFactory; |
| 13 | + |
| 14 | +public class FlitExceptionMapper implements ExceptionMapper<FlitException> { |
| 15 | + |
| 16 | + private static final Logger LOGGER = LoggerFactory.getLogger(FlitExceptionMapper.class); |
| 17 | + |
| 18 | + @Context private HttpServletRequest request; |
| 19 | + |
| 20 | + @Override |
| 21 | + public Response toResponse(FlitException exception) { |
| 22 | + LOGGER.error("Flit exception: request = {}, method = {}, code = {}, msg = {}", |
| 23 | + request.getRequestURI(), request.getMethod(), exception.getErrorCode(), |
| 24 | + exception.getMessage(), exception); |
| 25 | + |
| 26 | + Map<String, Object> response = new HashMap<>(); |
| 27 | + response.put("code", exception.getErrorCode().getErrorCode()); |
| 28 | + response.put("msg", exception.getMessage()); |
| 29 | + |
| 30 | + if (exception.hasMeta()) { |
| 31 | + response.put("meta", exception.getMeta()); |
| 32 | + } |
| 33 | + return Response.status(exception.getErrorCode().getHttpStatus()) |
| 34 | + .type(MediaType.APPLICATION_JSON) |
| 35 | + .entity(response) |
| 36 | + .build(); |
| 37 | + } |
| 38 | +} |
0 commit comments