org.springframework.web.server.ResponseStatusException Java Examples

The following examples show how to use org.springframework.web.server.ResponseStatusException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResponseStatusExceptionResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
protected ModelAndView doResolveException(
		HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

	try {
		if (ex instanceof ResponseStatusException) {
			return resolveResponseStatusException((ResponseStatusException) ex, request, response, handler);
		}

		ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
		if (status != null) {
			return resolveResponseStatus(status, request, response, handler, ex);
		}

		if (ex.getCause() instanceof Exception) {
			return doResolveException(request, response, handler, (Exception) ex.getCause());
		}
	}
	catch (Exception resolveEx) {
		if (logger.isWarnEnabled()) {
			logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", resolveEx);
		}
	}
	return null;
}
 
Example #2
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void createDataSource(DefaultSyndesisDataSource scd) throws AdminException {
    String syndesisName = scd.getSyndesisName();
    debug(syndesisName, "Creating the Datasource of Type " + scd.getType());

    if (scd.getTeiidName() == null) {
        for (int i = 0; i < 3; i++) {
            try {
                String name = getUniqueTeiidName(scd, syndesisName);
                scd.setTeiidName(name);
                break;
            } catch (PersistenceException | DataIntegrityViolationException ignored) {
                //multiple pods are trying to assign a name simultaneously
                //if we try again, then we'll just pickup whatever someone else set
            }
        }
        if (scd.getTeiidName() == null) {
            throw new ResponseStatusException(HttpStatus.CONFLICT);
        }
    }

    //now that the name is set, we can create the properties
    this.metadata.registerDataSource(scd);
}
 
Example #3
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_GENERIC_SERVICE_ERROR_returned_if_ResponseStatusException_with_ConversionNotSupportedException_cause_is_thrown() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(CONVERSION_NOT_SUPPORTED_EXCEPTION_ENDPOINT_PATH)
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, SampleCoreApiError.GENERIC_SERVICE_ERROR);
    ResponseStatusException ex = verifyExceptionSeenByBackstopper(ResponseStatusException.class);
    ConversionNotSupportedException cnse = verifyExceptionHasCauseOfType(ex, ConversionNotSupportedException.class);
    verifyHandlingResult(
        SampleCoreApiError.GENERIC_SERVICE_ERROR,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("bad_property_name", cnse.getPropertyName()),
        Pair.of("bad_property_value", cnse.getValue().toString()),
        Pair.of("required_type", cnse.getRequiredType().toString())
    );
}
 
Example #4
Source File: GraphAlgorithmHandler.java    From kafka-graphs with Apache License 2.0 6 votes vote down vote up
public Mono<ServerResponse> run(ServerRequest request) {
    List<String> appIdHeaders = request.headers().header(X_KGRAPH_APPID);
    String appId = request.pathVariable("id");
    return request.bodyToMono(GraphAlgorithmRunRequest.class)
        .flatMapMany(input -> {
            log.debug("num iterations: {}", input.getNumIterations());
            PregelGraphAlgorithm<?, ?, ?, ?> algorithm = algorithms.get(appId);
            GraphAlgorithmState state = algorithm.run(input.getNumIterations());
            GraphAlgorithmStatus status = new GraphAlgorithmStatus(state);
            Flux<GraphAlgorithmStatus> states =
                proxyRun(appIdHeaders.isEmpty() ? group.getCurrentMembers().keySet() : Collections.emptySet(), appId, input);
            return Mono.just(status).mergeWith(states);
        })
        .onErrorMap(RuntimeException.class, e -> new ResponseStatusException(NOT_FOUND))
        .reduce((state1, state2) -> state1)
        .flatMap(state ->
            ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(state), GraphAlgorithmStatus.class)
        );

}
 
Example #5
Source File: TAController.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{instrument}/{level:.+}",
method=RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public String getLevelBars(@PathVariable(value="instrument") String instrumentStr, @PathVariable(value="level") String level, @RequestParam(name="pretty", required=false) boolean pretty){
    Exchangeable instrument = Exchangeable.fromString(instrumentStr);
    TechnicalAnalysisAccess access = technicalAnalysisService.forInstrument(instrument);
    if ( access==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
    JsonElement json = null;
    PriceLevel l = PriceLevel.valueOf(level);
    BarSeries series = access.getSeries(l);
    if ( series==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
    json = JsonUtil.object2json(series);
    return (JsonUtil.json2str(json, pretty));
}
 
Example #6
Source File: UserAPI.java    From openvsx with Eclipse Public License 2.0 6 votes vote down vote up
@PostMapping(
    path = "/user/token/delete/{id}",
    produces = MediaType.APPLICATION_JSON_VALUE
)
@Transactional(rollbackOn = ResponseStatusException.class)
public ResultJson deleteAccessToken(@PathVariable long id) {
    var principal = users.getOAuth2Principal();
    if (principal == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN);
    }
    var user = users.updateUser(principal);
    var token = repositories.findAccessToken(id);
    if (token == null || !token.isActive() || !token.getUser().equals(user)) {
        return ResultJson.error("Token does not exist.");
    }
    token.setActive(false);
    return ResultJson.success("Deleted access token for user " + user.getLoginName());
}
 
Example #7
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_ResponseStatusException_with_TypeMismatchException_is_handled_generically_when_status_code_is_unexpected() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(TYPE_MISMATCH_WITH_UNEXPECTED_STATUS_ENDPOINT)
            .then()
            .log().all()
            .extract();

    // In this case the endpoint should throw a ResponseStatusException with a TypeMismatchException cause,
    //      but with an unexpected status code (403). Rather than treat it as a TypeMismatchException, we should
    //      get back a response that matches the desired status code.
    verifyErrorReceived(response, SampleCoreApiError.FORBIDDEN);
    ResponseStatusException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ResponseStatusException.class, 403
    );
    TypeMismatchException tme = verifyExceptionHasCauseOfType(ex, TypeMismatchException.class);
    verifyHandlingResult(
        SampleCoreApiError.FORBIDDEN,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage()))
    );
}
 
Example #8
Source File: UserAPI.java    From openvsx with Eclipse Public License 2.0 6 votes vote down vote up
@PostMapping(
    path = "/user/namespace/{namespace}/role",
    produces = MediaType.APPLICATION_JSON_VALUE
)
@Transactional(rollbackOn = ResponseStatusException.class)
public ResultJson setNamespaceMember(@PathVariable String namespace, @RequestParam String user,
        @RequestParam String role, @RequestParam(required = false) String provider) {
    var principal = users.getOAuth2Principal();
    if (principal == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN);
    }
    try {
        var requestingUser = users.updateUser(principal);
        return users.setNamespaceMember(requestingUser, namespace, provider, user, role);
    } catch (ErrorResultException exc) {
        return ResultJson.error(exc.getMessage());
    }
}
 
Example #9
Source File: ResourceWebHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void resourceNotFound(HttpMethod httpMethod) {
	MockServerHttpRequest request = MockServerHttpRequest.method(httpMethod, "").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	setPathWithinHandlerMapping(exchange, "not-there.css");
	Mono<Void> mono = this.handler.handle(exchange);

	StepVerifier.create(mono)
			.expectErrorSatisfies(err -> {
				assertThat(err, instanceOf(ResponseStatusException.class));
				assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus());
			}).verify(TIMEOUT);

	// SPR-17475
	AtomicReference<Throwable> exceptionRef = new AtomicReference<>();
	StepVerifier.create(mono).consumeErrorWith(exceptionRef::set).verify();
	StepVerifier.create(mono).consumeErrorWith(ex -> assertNotSame(exceptionRef.get(), ex)).verify();
}
 
Example #10
Source File: ConfigController.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{configSource}/**",
        method=RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getConfigItem(@PathVariable(value="configSource") String configSourceStr, HttpServletRequest request){
    String requestURI = request.getRequestURI();
    String configItem = requestURI.substring( URL_PREFIX.length()+configSourceStr.length()+1);
    Object obj = null;
    if ( "ALL".equalsIgnoreCase(configSourceStr) ) {
        obj = ConfigUtil.getObject(configItem);
    }else{
        String configSource = configSources.get(configSourceStr.toLowerCase());
        if (configSource==null){
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        obj = ConfigUtil.getObject(configSource, configItem);
    }
    if( logger.isDebugEnabled() ){
        logger.debug("Get config "+configSourceStr+" path \""+configItem+"\" value: \""+obj+"\"");
    }
    if ( obj==null ){
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }else{
        return obj.toString();
    }
}
 
Example #11
Source File: GateWayExceptionHandlerAdvice.java    From SpringCloud with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(value = {Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handle(Throwable throwable) {
    Result result = Result.fail();
    if (throwable instanceof ResponseStatusException) {
        result = handle((ResponseStatusException) throwable);
    } else if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof NotFoundException) {
        result = handle((NotFoundException) throwable);
    } else if (throwable instanceof RuntimeException) {
        result = handle((RuntimeException) throwable);
    } else if (throwable instanceof Exception) {
        result = handle((Exception) throwable);
    }
    return result;
}
 
Example #12
Source File: RouterFunctionsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void toHttpHandlerHandlerReturnResponseStatusExceptionInResponseWriteTo() {
	HandlerFunction<ServerResponse> handlerFunction =
			// Mono.<ServerResponse> is required for compilation in Eclipse
			request -> Mono.just(new ServerResponse() {
				@Override
				public HttpStatus statusCode() {
					return HttpStatus.OK;
				}
				@Override
				public HttpHeaders headers() {
					return new HttpHeaders();
				}
				@Override
				public MultiValueMap<String, ResponseCookie> cookies() {
					return new LinkedMultiValueMap<>();
				}
				@Override
				public Mono<Void> writeTo(ServerWebExchange exchange, Context context) {
					return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
				}
			});
	RouterFunction<ServerResponse> routerFunction =
			RouterFunctions.route(RequestPredicates.all(), handlerFunction);

	HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
	assertNotNull(result);

	MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
	MockServerHttpResponse httpResponse = new MockServerHttpResponse();
	result.handle(httpRequest, httpResponse).block();
	assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
 
Example #13
Source File: OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "400    |   Request body is missing             |   MISSING_EXPECTED_CONTENT",
    "400    |   Request body is missing blahblah    |   MISSING_EXPECTED_CONTENT",
    "401    |   Request body is missing             |   UNAUTHORIZED",
    "400    |   Request body is                     |   GENERIC_BAD_REQUEST",
    "400    |   Some random reason                  |   GENERIC_BAD_REQUEST",
}, splitBy = "\\|")
@Test
public void handleFluxExceptions_returns_MISSING_EXPECTED_CONTENT_for_ResponseStatusException_with_special_reason_string_beginning(
    int statusCode, String exReasonString, BarebonesCoreApiErrorForTesting expectedError
) {
    // given
    ResponseStatusException ex = new ResponseStatusException(HttpStatus.resolve(statusCode), exReasonString);
    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>();
    ApiExceptionHandlerUtils.DEFAULT_IMPL.addBaseExceptionMessageToExtraDetailsForLogging(
        ex, expectedExtraDetailsForLogging
    );

    // when
    ApiExceptionHandlerListenerResult result = listener.handleSpringMvcOrWebfluxSpecificFrameworkExceptions(ex);

    // then
    validateResponse(
        result,
        true,
        singleton(expectedError),
        expectedExtraDetailsForLogging
    );
}
 
Example #14
Source File: ResourceWebHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void missingResourcePath() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
	setPathWithinHandlerMapping(exchange, "");
	StepVerifier.create(this.handler.handle(exchange))
			.expectErrorSatisfies(err -> {
				assertThat(err, instanceOf(ResponseStatusException.class));
				assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus());
			}).verify(TIMEOUT);
}
 
Example #15
Source File: StateRepositoryUiController.java    From synapse with Apache License 2.0 5 votes vote down vote up
@GetMapping(
        path = "${edison.application.management.base-path:internal}/staterepositories/{repositoryName}/{entityId}",
        produces = "text/html"
)
public ModelAndView getEntityHtml(final @PathVariable String repositoryName,
                                  final @PathVariable String entityId) {
    final StateRepository<?> stateRepository = stateRepositories.get(repositoryName);
    if (stateRepository != null) {

        List<ImmutableMap<String,String>> entities = stateRepository.get(entityId).isPresent()
                ? singletonList(toEntityModel(entityId, stateRepository.get(entityId).get()))
                : emptyList();

        return new ModelAndView(
                "staterepository",
                ImmutableMap.<String,Object>builder()
                        .put("basePath", managementBasePath)
                        .put("singleEntity", true)
                        .put("journaled", journals.hasJournal(repositoryName))
                        .put("repositoryName", repositoryName)
                        .put("entities", entities)
                        .put("pager", UNAVAILABLE)
                        .build()
        );
    } else {
        throw new ResponseStatusException(NOT_FOUND, "No such StateRepository " + repositoryName);
    }
}
 
Example #16
Source File: OperationsApiServiceImpl.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private String getAuthenticatedUser(HttpServletRequest request) {
    String user = null;
    if (request.getUserPrincipal() != null) {
        user = request.getUserPrincipal()
                      .getName();
    } else {
        throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    LOGGER.debug(MessageFormat.format("Authenticated user is: {0}", user));
    return user;
}
 
Example #17
Source File: SpaceGuidBasedAuthorizationFilter.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public final boolean ensureUserIsAuthorized(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String spaceGuid = extractAndLogSpaceGuid(request);
    try {
        authorizationChecker.ensureUserIsAuthorized(request, SecurityContextUtil.getUserInfo(), spaceGuid, null);
        return true;
    } catch (ResponseStatusException e) {
        logUnauthorizedRequest(request, e);
        response.sendError(HttpStatus.UNAUTHORIZED.value(),
                           MessageFormat.format(Messages.NOT_AUTHORIZED_TO_OPERATE_IN_SPACE_WITH_GUID_0, spaceGuid));
        return false;
    }
}
 
Example #18
Source File: ResponseStatusExceptionHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine the HTTP status implied by the given exception.
 * @param ex the exception to introspect
 * @return the associated HTTP status, if any
 * @since 5.0.5
 */
@Nullable
protected HttpStatus determineStatus(Throwable ex) {
	if (ex instanceof ResponseStatusException) {
		return ((ResponseStatusException) ex).getStatus();
	}
	return null;
}
 
Example #19
Source File: TeiidRSProvider.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private InputStream handleResult(String charSet, Object result) {
    if (result == null) {
        return null; // or should this be an empty result?
    }
    try {
        if (result instanceof SQLXML) {
            if (charSet != null) {
                XMLSerialize serialize = new XMLSerialize();
                serialize.setTypeString("blob"); //$NON-NLS-1$
                serialize.setDeclaration(true);
                serialize.setEncoding(charSet);
                serialize.setDocument(true);
                return ((BlobType) XMLSystemFunctions.serialize(serialize, new XMLType((SQLXML) result)))
                        .getBinaryStream();
            }
            return ((SQLXML) result).getBinaryStream();
        } else if (result instanceof Blob) {
            return ((Blob) result).getBinaryStream();
        } else if (result instanceof Clob) {
            return new ReaderInputStream(((Clob) result).getCharacterStream(),
                    charSet == null ? Charset.defaultCharset() : Charset.forName(charSet));
        }
        return new ByteArrayInputStream(
                result.toString().getBytes(charSet == null ? Charset.defaultCharset() : Charset.forName(charSet)));
    } catch (SQLException | TransformationException e) {
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }
}
 
Example #20
Source File: RouterFunctionsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void toHttpHandlerHandlerResponseStatusException() {
	HandlerFunction<ServerResponse> handlerFunction =
			request -> Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
	RouterFunction<ServerResponse> routerFunction =
			RouterFunctions.route(RequestPredicates.all(), handlerFunction);

	HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
	assertNotNull(result);

	MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
	MockServerHttpResponse httpResponse = new MockServerHttpResponse();
	result.handle(httpRequest, httpResponse).block();
	assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
 
Example #21
Source File: UserApiDelegateImpl.java    From openapi-petstore with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<Void> deleteUser(String username) {
    User user = userRepository.findById(username)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
    userRepository.delete(user);
    return ResponseEntity.ok().build();
}
 
Example #22
Source File: PetApiDelegateImpl.java    From openapi-petstore with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<List<Pet>> findPetsByStatus(List<String> statusList) {
    List<Pet.StatusEnum> statusEnums = statusList.stream()
            .map(s -> Optional.ofNullable(Pet.StatusEnum.fromValue(s))
                    .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid status: " + s))
            )
            .collect(Collectors.toList());
    return ResponseEntity.ok(petRepository.findPetsByStatus(statusEnums));
}
 
Example #23
Source File: ResponseStatusExceptionHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-16231
public void responseCommitted() {
	Throwable ex = new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Oops");
	this.exchange.getResponse().setStatusCode(HttpStatus.CREATED);
	Mono<Void> mono = this.exchange.getResponse().setComplete()
			.then(Mono.defer(() -> this.handler.handle(this.exchange, ex)));
	StepVerifier.create(mono).consumeErrorWith(actual -> assertSame(ex, actual)).verify();
}
 
Example #24
Source File: TeiidRSProvider.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public ResponseEntity<InputStreamResource> executeQuery(final String sql, boolean json, final boolean passthroughAuth)
        throws SQLException {
    Connection conn = null;
    try {
        conn = getConnection();
        Statement statement = conn.createStatement();
        final boolean hasResultSet = statement.execute(sql);
        Object result = null;
        if (hasResultSet) {
            ResultSet rs = statement.getResultSet();
            if (rs.next()) {
                result = rs.getObject(1);
            } else {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"Only result producing procedures are allowed");
            }
        }
        InputStream is = handleResult(Charset.defaultCharset().name(), result);
        InputStreamResource inputStreamResource = new InputStreamResource(is);
        HttpHeaders httpHeaders = new HttpHeaders();
        return new ResponseEntity<InputStreamResource>(inputStreamResource, httpHeaders, HttpStatus.OK);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
        }
    }
}
 
Example #25
Source File: SpringCloudInfoRestController.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@GetMapping("/springcloudversion/springboot/{bootVersion}")
public SpringCloudVersion version(@PathVariable String bootVersion) {
	try {
		return versionService.getSpringCloudVersion(bootVersion);
	}
	catch (SpringCloudVersionNotFoundException e) {
		throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
	}
}
 
Example #26
Source File: FooController.java    From tutorials with MIT License 5 votes vote down vote up
@PostMapping("/foos")
@ResponseStatus(HttpStatus.CREATED)    
public void create( @RequestBody final Foo foo) {
    if (null == foo ||  null == foo.getName()) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST," 'name' is required");
    }
    repo.save(foo);
}
 
Example #27
Source File: ErrorExceptionHandler.java    From SpringBlade with Apache License 2.0 5 votes vote down vote up
/**
 * 获取异常属性
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
	int code = 500;
	Throwable error = super.getError(request);
	if (error instanceof NotFoundException) {
		code = 404;
	}
	if (error instanceof ResponseStatusException) {
		code = ((ResponseStatusException) error).getStatus().value();
	}
	return ResponseProvider.response(code, this.buildMessage(request, error));
}
 
Example #28
Source File: SpringCloudInfoRestController.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@GetMapping("/bomversions/{bomVersion}")
public Map<String, String> bomVersions(@PathVariable String bomVersion)
		throws IOException {
	try {
		return versionService.getReleaseVersions(bomVersion);
	}
	catch (SpringCloudVersionNotFoundException e) {
		throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
	}

}
 
Example #29
Source File: FebsGatewayExceptionHandler.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 异常处理,定义返回报文格式
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Throwable error = super.getError(request);
    log.error(
            "请求发生异常,请求URI:{},请求方法:{},异常信息:{}",
            request.path(), request.methodName(), error.getMessage()
    );
    String errorMessage;
    if (error instanceof NotFoundException) {
        String serverId = StringUtils.substringAfterLast(error.getMessage(), "Unable to find instance for ");
        serverId = StringUtils.replace(serverId, "\"", StringUtils.EMPTY);
        errorMessage = String.format("无法找到%s服务", serverId);
    } else if (StringUtils.containsIgnoreCase(error.getMessage(), "connection refused")) {
        errorMessage = "目标服务拒绝连接";
    } else if (error instanceof TimeoutException) {
        errorMessage = "访问服务超时";
    } else if (error instanceof ResponseStatusException
            && StringUtils.containsIgnoreCase(error.getMessage(), HttpStatus.NOT_FOUND.toString())) {
        errorMessage = "未找到该资源";
    } else {
        errorMessage = "网关转发异常";
    }
    Map<String, Object> errorAttributes = new HashMap<>(3);
    errorAttributes.put("message", errorMessage);
    return errorAttributes;
}
 
Example #30
Source File: SpaceNameBasedAuthorizationFilter.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private void logUnauthorizedRequest(HttpServletRequest request, ResponseStatusException e) {
    if (LOGGER.isDebugEnabled()) {
        String userName = SecurityContextUtil.getUserName();
        LOGGER.debug(String.format("User \"%s\" is not authorized for request to \"%s\".", userName, ServletUtil.decodeUri(request)),
                     e);
    }
}