001/** 002 * Copyright (C) 2006-2021 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.talend.sdk.component.server.front.error; 017 018import static javax.ws.rs.core.MediaType.WILDCARD_TYPE; 019 020import java.util.Optional; 021 022import javax.annotation.PostConstruct; 023import javax.enterprise.context.Dependent; 024import javax.inject.Inject; 025import javax.ws.rs.WebApplicationException; 026import javax.ws.rs.core.Response; 027import javax.ws.rs.ext.ExceptionMapper; 028import javax.ws.rs.ext.Provider; 029 030import org.talend.sdk.component.server.configuration.ComponentServerConfiguration; 031import org.talend.sdk.component.server.front.model.ErrorDictionary; 032import org.talend.sdk.component.server.front.model.error.ErrorPayload; 033 034import lombok.extern.slf4j.Slf4j; 035 036@Slf4j 037@Dependent 038@Provider 039public class DefaultExceptionHandler implements ExceptionMapper<Throwable> { 040 041 @Inject 042 private ComponentServerConfiguration configuration; 043 044 private boolean replaceException; 045 046 @PostConstruct 047 private void init() { 048 replaceException = !"false".equalsIgnoreCase(configuration.getDefaultExceptionMessage()); 049 } 050 051 @Override 052 public Response toResponse(final Throwable exception) { 053 final Response response; 054 if (WebApplicationException.class.isInstance(exception)) { 055 response = WebApplicationException.class.cast(exception).getResponse(); 056 } else { 057 final Optional<Throwable> optCause = Optional.ofNullable(exception.getCause()); 058 if (optCause.isPresent()) { 059 final Throwable cause = optCause.get(); 060 if (WebApplicationException.class.isInstance(cause)) { 061 response = WebApplicationException.class.cast(cause).getResponse(); 062 } else { 063 response = Response 064 .status(Response.Status.INTERNAL_SERVER_ERROR) 065 .entity(new ErrorPayload(ErrorDictionary.UNEXPECTED, 066 replaceException ? configuration.getDefaultExceptionMessage() : cause.getMessage())) 067 .type(WILDCARD_TYPE) 068 .build(); 069 } 070 } else { 071 response = Response 072 .status(Response.Status.INTERNAL_SERVER_ERROR) 073 .entity(new ErrorPayload(ErrorDictionary.UNEXPECTED, 074 replaceException ? configuration.getDefaultExceptionMessage() : exception.getMessage())) 075 .type(WILDCARD_TYPE) 076 .build(); 077 } 078 } 079 return response; 080 } 081 082}