Best Testsigma code snippet using com.testsigma.agent.dto.APIErrorDTO
Source:GlobalExceptionHandler.java
...4 * All rights reserved.5 * ****************************************************************************6 */7package com.testsigma.exception;8import com.testsigma.dto.APIErrorDTO;9import com.testsigma.dto.FieldErrorDTO;10import com.testsigma.mapper.FieldErrorMapper;11import lombok.RequiredArgsConstructor;12import lombok.extern.log4j.Log4j2;13import org.springframework.beans.TypeMismatchException;14import org.springframework.dao.DataIntegrityViolationException;15import org.springframework.http.HttpHeaders;16import org.springframework.http.HttpStatus;17import org.springframework.http.ResponseEntity;18import org.springframework.validation.BindException;19import org.springframework.web.HttpMediaTypeNotSupportedException;20import org.springframework.web.HttpRequestMethodNotSupportedException;21import org.springframework.web.bind.MethodArgumentNotValidException;22import org.springframework.web.bind.MissingServletRequestParameterException;23import org.springframework.web.bind.annotation.ControllerAdvice;24import org.springframework.web.bind.annotation.ExceptionHandler;25import org.springframework.web.context.request.WebRequest;26import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;27import org.springframework.web.multipart.support.MissingServletRequestPartException;28import org.springframework.web.servlet.NoHandlerFoundException;29import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;30import javax.validation.ConstraintViolation;31import javax.validation.ConstraintViolationException;32import java.util.ArrayList;33import java.util.List;34@ControllerAdvice35@Log4j236@RequiredArgsConstructor37public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {38 private final FieldErrorMapper errorMapper;39 //This exception is thrown when argument annotated with @Valid failed validation:40 @Override41 protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex,42 final HttpHeaders headers, final HttpStatus status,43 final WebRequest request) {44 logger.error(ex.getMessage(), ex);45 final APIErrorDTO apiError = new APIErrorDTO();46 apiError.setError(ex.getLocalizedMessage());47 apiError.setFieldErrors(errorMapper.map(ex.getBindingResult().getFieldErrors()));48 apiError.setObjectErrors(errorMapper.mapObjectErrors(ex.getBindingResult().getGlobalErrors()));49 return handleExceptionInternal(ex, apiError, headers, HttpStatus.BAD_REQUEST, request);50 }51 //This exception is thrown when fatal binding errors occur.52 @Override53 protected ResponseEntity<Object> handleBindException(final BindException ex, final HttpHeaders headers,54 final HttpStatus status, final WebRequest request) {55 logger.error(ex.getMessage(), ex);56 final APIErrorDTO apiError = new APIErrorDTO();57 apiError.setError(ex.getLocalizedMessage());58 apiError.setFieldErrors(errorMapper.map(ex.getBindingResult().getFieldErrors()));59 apiError.setObjectErrors(errorMapper.mapObjectErrors(ex.getBindingResult().getGlobalErrors()));60 return handleExceptionInternal(ex, apiError, headers, HttpStatus.BAD_REQUEST, request);61 }62 //This exception is thrown when there is type mis match of parameter63 @Override64 protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers,65 final HttpStatus status, final WebRequest request) {66 logger.error(ex.getMessage(), ex);67 final APIErrorDTO apiError = new APIErrorDTO();68 apiError.setError(ex.getLocalizedMessage());69 List<FieldErrorDTO> fieldErrorDTOS = new ArrayList<>();70 FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();71 fieldErrorDTO.setField(ex.getPropertyName());72 fieldErrorDTO.setMessage(" value should be of type " + ex.getRequiredType());73 fieldErrorDTO.setRejectedValue(ex.getValue());74 fieldErrorDTOS.add(fieldErrorDTO);75 apiError.setFieldErrors(fieldErrorDTOS);76 return new ResponseEntity<>(apiError, headers, HttpStatus.BAD_REQUEST);77 }78 //This exception is thrown when when the part of a multipart request not found79 @Override80 protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex,81 final HttpHeaders headers, final HttpStatus status,82 final WebRequest request) {83 logger.error(ex.getMessage(), ex);84 final APIErrorDTO apiError = new APIErrorDTO();85 apiError.setError(ex.getLocalizedMessage());86 List<FieldErrorDTO> fieldErrorDTOS = new ArrayList<>();87 FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();88 fieldErrorDTO.setField(ex.getRequestPartName());89 fieldErrorDTO.setMessage(" part is missing");90 apiError.setFieldErrors(fieldErrorDTOS);91 return new ResponseEntity<>(apiError, headers, HttpStatus.BAD_REQUEST);92 }93 //This exception is thrown when request missing parameter:94 @Override95 protected ResponseEntity<Object> handleMissingServletRequestParameter(96 final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatus status,97 final WebRequest request) {98 logger.error(ex.getMessage(), ex);99 final APIErrorDTO apiError = new APIErrorDTO();100 apiError.setError(ex.getLocalizedMessage());101 List<FieldErrorDTO> fieldErrorDTOS = new ArrayList<>();102 FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();103 fieldErrorDTO.setField(ex.getParameterName());104 fieldErrorDTO.setMessage(" parameter is missing");105 apiError.setFieldErrors(fieldErrorDTOS);106 return new ResponseEntity<>(apiError, headers, HttpStatus.BAD_REQUEST);107 }108 //This exception is thrown when method argument is not the expected type:109 @ExceptionHandler({MethodArgumentTypeMismatchException.class})110 public ResponseEntity<Object> handleMethodArgumentTypeMismatch(final MethodArgumentTypeMismatchException ex,111 final WebRequest request) {112 logger.error(ex.getMessage(), ex);113 final APIErrorDTO apiError = new APIErrorDTO();114 apiError.setError(ex.getLocalizedMessage());115 List<FieldErrorDTO> fieldErrorDTOS = new ArrayList<>();116 FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();117 fieldErrorDTO.setField(ex.getName());118 fieldErrorDTO.setMessage(" should be of type " + ex.getRequiredType().getName());119 apiError.setFieldErrors(fieldErrorDTOS);120 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST);121 }122 //This exception reports the result of constraint violations:123 @ExceptionHandler({ConstraintViolationException.class})124 public ResponseEntity<Object> handleConstraintViolation(final ConstraintViolationException ex,125 final WebRequest request) {126 logger.error(ex.getMessage(), ex);127 final APIErrorDTO apiError = new APIErrorDTO();128 apiError.setError(ex.getLocalizedMessage());129 final List<FieldErrorDTO> errors = new ArrayList<FieldErrorDTO>();130 for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) {131 FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();132 fieldErrorDTO.setField(violation.getRootBeanClass().getName() + " " + violation.getPropertyPath());133 fieldErrorDTO.setMessage(violation.getMessage());134 }135 apiError.setFieldErrors(errors);136 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST);137 }138 // 404139 @Override140 protected ResponseEntity<Object> handleNoHandlerFoundException(final NoHandlerFoundException ex,141 final HttpHeaders headers, final HttpStatus status,142 final WebRequest request) {143 logger.error(ex.getMessage(), ex);144 final String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();145 final APIErrorDTO apiError = new APIErrorDTO();146 apiError.setError(error);147 return new ResponseEntity<>(apiError, headers, HttpStatus.NOT_FOUND);148 }149 // 405150 @Override151 protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex,152 final HttpHeaders headers,153 final HttpStatus status,154 final WebRequest request) {155 logger.error(ex.getMessage(), ex);156 final StringBuilder builder = new StringBuilder();157 builder.append(ex.getMethod());158 builder.append(" method is not supported for this request. Supported methods are ");159 ex.getSupportedHttpMethods().forEach(t -> builder.append(t + " "));160 final APIErrorDTO apiError = new APIErrorDTO();161 apiError.setError(builder.toString());162 return new ResponseEntity<>(apiError, headers, HttpStatus.METHOD_NOT_ALLOWED);163 }164 // 415165 @Override166 protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(final HttpMediaTypeNotSupportedException ex,167 final HttpHeaders headers, final HttpStatus status,168 final WebRequest request) {169 logger.error(ex.getMessage(), ex);170 final StringBuilder builder = new StringBuilder();171 builder.append(ex.getContentType());172 builder.append(" media type is not supported. Supported media types are ");173 ex.getSupportedMediaTypes().forEach(t -> builder.append(t + " "));174 final APIErrorDTO apiError = new APIErrorDTO();175 apiError.setError(builder.toString());176 return new ResponseEntity<>(apiError, headers, HttpStatus.UNSUPPORTED_MEDIA_TYPE);177 }178 @ExceptionHandler({ResourceNotFoundException.class})179 public ResponseEntity<Object> handle(final ResourceNotFoundException ex) {180 log.error(ex.getMessage(), ex);181 final APIErrorDTO apiError = new APIErrorDTO();182 apiError.setError(ex.getLocalizedMessage());183 apiError.setCode(ex.getErrorCode());184 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.NOT_FOUND);185 }186 @ExceptionHandler({JwtTokenMissingException.class})187 public ResponseEntity<Object> handle(final JwtTokenMissingException ex) {188 log.error(ex.getMessage(), ex);189 final APIErrorDTO apiError = new APIErrorDTO();190 apiError.setError(ex.getMessage());191 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAUTHORIZED);192 }193 @ExceptionHandler({InValidJwtTokenException.class})194 public ResponseEntity<Object> handle(final InValidJwtTokenException ex) {195 log.error(ex.getMessage(), ex);196 final APIErrorDTO apiError = new APIErrorDTO();197 apiError.setError(ex.getMessage());198 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAUTHORIZED);199 }200 @ExceptionHandler({AgentDeletedException.class})201 public ResponseEntity<Object> handleAgentDeleted(final AgentDeletedException ex) {202 log.error(ex.getMessage(), ex);203 final APIErrorDTO apiError = new APIErrorDTO();204 apiError.setError(ex.getMessage());205 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.PRECONDITION_FAILED);206 }207 @ExceptionHandler({TestsigmaRunTimeDataNotException.class})208 public ResponseEntity<Object> handleRuntime(final TestsigmaRunTimeDataNotException ex) {209 log.error(ex.getMessage(), ex);210 final APIErrorDTO apiError = new APIErrorDTO();211 apiError.setError(ex.getMessage());212 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.NOT_FOUND);213 }214 @ExceptionHandler({NotLocalAgentRegistrationException.class})215 public ResponseEntity<Object> handleRuntime(final NotLocalAgentRegistrationException ex) {216 log.error(ex.getMessage(), ex);217 final APIErrorDTO apiError = new APIErrorDTO();218 apiError.setError(ex.getMessage());219 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.PRECONDITION_FAILED);220 }221 @ExceptionHandler({TestsigmaException.class})222 public ResponseEntity<Object> handleTestsigmaException(final TestsigmaException ex, final WebRequest request) {223 logger.error(ex.getMessage(), ex);224 final APIErrorDTO apiError = new APIErrorDTO();225 apiError.setCode(ex.getErrorCode());226 apiError.setError(ex.getLocalizedMessage());227 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);228 }229 @ExceptionHandler({IntegrationNotFoundException.class})230 public ResponseEntity<Object> handleTestsigmaException(final IntegrationNotFoundException ex,231 final WebRequest request) {232 logger.error(ex.getMessage(), ex);233 final APIErrorDTO apiError = new APIErrorDTO();234 apiError.setCode(ex.getErrorCode());235 apiError.setError(ex.getLocalizedMessage());236 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST);237 }238 // 500239 @ExceptionHandler({Exception.class})240 public ResponseEntity<Object> handleAll(final Exception ex, final WebRequest request) {241 log.error(ex.getMessage(), ex);242 final APIErrorDTO apiError = new APIErrorDTO();243 apiError.setError(ex.getLocalizedMessage());244 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);245 }246 @ExceptionHandler({org.springframework.dao.DataIntegrityViolationException.class})247 public ResponseEntity<Object> handleDuplicateName(final DataIntegrityViolationException ex) {248 ex.printStackTrace();249 log.error(ex.getMessage(), ex);250 if (ex.getMessage().contains("Cannot delete or update a parent row")){251 final APIErrorDTO apiError = new APIErrorDTO();252 apiError.setError("Entity has some relation please check it out");253 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS);254 }255 if (ex.getCause().getCause().getClass().equals(java.sql.SQLIntegrityConstraintViolationException.class) &&256 ex.getCause().getCause().getMessage().contains("Duplicate entry")) {257 final APIErrorDTO apiError = new APIErrorDTO();258 apiError.setError("Entity with same name already exists, Please use different name");259 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY);260 } else if (ex.getCause().getCause().getClass().equals(java.sql.SQLIntegrityConstraintViolationException.class) &&261 ex.getCause().getCause().getMessage().contains("component_id_key")) {262 final APIErrorDTO apiError = new APIErrorDTO();263 apiError.setError("Can not delete step Group because it is referenced in another Test Case");264 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS);265 } else if (ex.getCause().getCause().getClass().equals(java.sql.SQLIntegrityConstraintViolationException.class) &&266 ex.getCause().getCause().getMessage().contains("Cannot delete or update a parent row")) {267 final APIErrorDTO apiError = new APIErrorDTO();268 apiError.setError("Entity has some relation please check it out");269 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS);270 } else {271 final APIErrorDTO apiError = new APIErrorDTO();272 apiError.setError(ex.getMessage());273 return new ResponseEntity<>(apiError,274 new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);275 }276 }277 @ExceptionHandler({InvalidStorageCredentialsException.class})278 public ResponseEntity<Object> handleTestsigmaException(final InvalidStorageCredentialsException ex,279 final WebRequest request) {280 logger.error(ex.getMessage(), ex);281 final APIErrorDTO apiError = new APIErrorDTO();282 apiError.setCode(ex.getErrorCode());283 apiError.setError(ex.getLocalizedMessage());284 return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.UNAUTHORIZED);285 }286}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!