Bad request exception java

Java BadRequestException BadRequestException(Response response, Throwable cause)

Java BadRequestException BadRequestException(Response response, Throwable cause) Construct a new bad client request exception.

Introduction

The method BadRequestException() is a constructor.

Syntax

The method BadRequestException() from BadRequestException is declared as:

public BadRequestException(Response response, Throwable cause) 

The method BadRequestException() has the following parameter:

  • Responseresponse — error response.
  • Throwablecause — the underlying cause of the exception.

The method BadRequestException() throws the following exceptions:

Example

The following code shows how to use BadRequestException from javax.ws.rs.

Specifically, the code shows you how to use Java BadRequestException BadRequestException(Response response, Throwable cause)

import java.text.ParseException; import java.time.LocalDateTime; import javax.ws.rs.BadRequestException; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import com.example.util.DateConverter; import com.nimbusds.jwt.ReadOnlyJWTClaimsSet; import com.nimbusds.jwt.SignedJWT; final class SecurityContextProvider implements ISecurityContextProvider < @Override/*w w w . d e m o 2s . c o m */ public SecurityContext get(SignedJWT jwt, UriInfo uriInfo) < ReadOnlyJWTClaimsSet claims; try < claims = jwt.getJWTClaimsSet(); >catch (ParseException e) < throw new BadRequestException(e.getMessage(), e); > if (isExpired(claims)) < throw new AuthenticationException(Status.FORBIDDEN, "Token expired."); > return new JWTSecurityContext(claims, uriInfo.getRequestUri().getScheme()); > private boolean isExpired(ReadOnlyJWTClaimsSet claims) < return DateConverter.getDateTime(claims.getExpirationTime()).isBefore(LocalDateTime.now()); > >
import java.text.ParseException; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.core.Response.Status; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jwt.SignedJWT; final class AuthenticationTokenVerifier implements IAuthenticationTokenVerifier < private final JWSVerifier verifier; @Inject// w w w. d e m o 2 s . c o m public AuthenticationTokenVerifier(JWSVerifier verifier) < this.verifier = verifier; > @Override public SignedJWT verify(String token) < boolean verified = false; SignedJWT jwt; try < jwt = SignedJWT.parse(token); verified = jwt.verify(verifier); >catch (ParseException | JOSEException e) < throw new BadRequestException(e.getMessage(), e); > if (!verified) < throw new AuthenticationException(Status.FORBIDDEN, "Token could not be verified."); > return jwt; > >
import java.io.IOException; import java.security.GeneralSecurityException; import java.security.interfaces.RSAPrivateKey; import javax.ws.rs.BadRequestException; import javax.ws.rs.ForbiddenException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import yushijinhun.authlibagent.service.SignatureService; import yushijinhun.authlibagent.util.KeyUtils; @Component("keyResource") public class KeyResourceImpl implements KeyResource < @Value("#") private boolean allowDownloadPrivateKey; @Value("#") private boolean allowUploadPrivateKey; @Autowired// w w w . d e m o 2 s . c o m private SignatureService signatureService; @Override public byte[] getEncodedKey() < if (!allowDownloadPrivateKey) < throw new ForbiddenException("It is not allowed to download the private key"); > RSAPrivateKey key = signatureService.getKey(); return key == null ? new byte[0] : key.getEncoded(); > @Override public void setEncodedKey(byte[] key) throws IOException < if (!allowUploadPrivateKey) < throw new ForbiddenException("It is not allowed to upload a private key"); > try < signatureService.setKey(key.length == 0 ? null : KeyUtils.fromPKCS8(key)); >catch (GeneralSecurityException e) < throw new BadRequestException("Invalid key: " + e, e); > > >

  • Java BadRequestException BadRequestException()
  • Java BadRequestException BadRequestException(String message, Response response)
  • Java BadRequestException BadRequestException(String message, Throwable cause)
  • Java BadRequestException BadRequestException(Response response, Throwable cause)
  • Java BadRequestException getResponse()
  • Java javax.ws.rs ClientErrorException
  • javax.ws.rs ClientErrorException tutorial with examples

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Detect and Handle a 400 Bad Request Exception

To handle exceptions in both the application and API layers, I utilized a pattern that allows the API layer to identify the HTTP status code. The exceptions were defined and an action filter was set up to handle them in the API layer. This way, when exceptions are thrown in the application layer, the API call will return a JSON with an error message and HTTP 400 status code. Alternatively, if String is not being used, values that exceed the max value of long can be stored using BigInteger.

Catch a Bad Request Exception (400)

Within my Facade/EJB, there exists a straightforward procedure in which I carry out a task by means of a method.

Within the controller, I invoke an EJB and define a method that requires non-null parameters. Subsequently, I attempt to handle any exceptions that may arise in the following manner:

The issue is that I am unable to capture exceptions.

In my Web method, I resolved the issue by utilizing the NotNull annotation, which ensures that the exception is never invoked.

Rest — Is it good practice to raise an exception on «bad, In the special case of HTTP endpoints I can always give a meaningful answer — a response with a status code. Handling bad requests thus belongs to normal program flow of endpoint methods and should not raise new exception. E.g. an endpoint that returns a resource should just return 404 in case the resource is …

How to catch the exception for bad request

When I send the request, I am unable to catch the exception. Although the datatype of empno is long, I still send a value greater than the maximum allowed for long. Despite using both @Min and @Max annotations in my pojo class, the issue persists. However, my requirement does not allow me to use a string in place of long.

public class Personal < private long empNo; public void setEmpNo(long empNo) < this.empNo = empNo; >public long getEmpNo() < return this.empNo; >> @RestController @RequestMapping(value = "/employee/v1") public class EmployeeController < public ResponseEntitygetLocationService(HttpServletRequest httpServletRequest, @Valid @RequestBody Personal personal, HttpServletResponse httpResponse) < . Business Logic >> 

To handle larger numbers, it is recommended to use BigInteger instead of Long. Another option is to read the number as a String in the request object and then parse it to a long using Long.parseLong(stringValue) in the service tier. This approach can be wrapped in a try/catch block to handle any exceptions that may arise.

In case String is not utilized, BigInteger can be employed for storing values that surpass the long’s maximum value. As an illustration:

public class Personal < private BigInteger empNo; public void setEmpNo(BigInteger empNo) < this.empNo = empNo; >public BigInteger getEmpNo() < return this.empNo; >>
BigInteger bd = new BigInteger("922337203685477582012312321"); System.out.println(bd.multiply(new BigInteger("15"))); System.out.println(bd); 
13835058055282163730184684815 922337203685477582012312321 

For further information, this link can be referred to: https://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html

Troubleshoot Azure Cosmos DB bad request exceptions, The HTTP status code 400 represents the request contains invalid data or it’s missing required parameters. Missing the ID property On this scenario, it’s common to see the error: The input content is invalid because the required properties — ‘id; ‘ — are missing

Which system exception for Bad Request

In my API-controller that invokes service class, I aim to throw an exception within the service class. This would enable the API-controller to capture it and then respond with a Http-BadRequest. However, I am unsure which exception is suitable for a Bad Request and what the recommended approach is for such a scenario.

The design I implemented for throwing exceptions was utilized in both the application layer and the API layer to identify the corresponding HTTP status code.

The exceptions definition:

public class BadRequestException : Exception < public BadRequestException(string message = null) : base(message == null ? "Bad Request" : message) < >> public class ActionInputIsNotValidException : BadRequestException < public ActionInputIsNotValidException() : base("Action input is not valid") < >> 

A filter designed to manage exceptions occurring in the API layer.

public class ExceptionActionFilter : ExceptionFilterAttribute < public ExceptionActionFilter() < >public override void OnException(ExceptionContext context) < context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.HttpContext.Response.ContentType = "application/json"; if (isTypeOf(context.Exception, typeof(Exceptions.BadRequestException))) < context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; >context.Result = new JsonResult(new < Message = context.Exception.Message, >); > private bool isTypeOf(Exception exception, Type baseType) < return exception.GetType() == baseType || exception.GetType().IsSubclassOf(baseType); >> 

In the application layer, throwing exceptions can generate a JSON response with a HTTP 400 status code that includes error message.

throw new ActionInputIsNotValidException(); 

HTTP 400 Bad Request Error C#, Whenever you see an error that includes a three-digit HTTP status code, that means that you were able to send the request over the network and were able to get a response. The status code is actually provided by the server, not raised by the .NET runtime or anything on your side.

HttpClientErrorException$BadRequest: 400 : [no body] when calling restTemplate.postForObject

I am utilizing a SpringBoot’s POST service named getOrder3, which is working fine as verified through Postman. However, an error is occurring when I call it through restTemplate.postForObject from another service. I have tested two versions of the client service, namely getOrderClient and getOrderClient2, but both are producing the same error.

An error occurred while trying to use the HttpClient. The error message reads as follows: HttpClientErrorException$BadRequest: 400 : [no body].

Kindly review the information provided and any assistance rendered would be highly valued.

@PostMapping(value="/getOrder3/",produces="application/json") public ResponseEntity getOrder3( @PathVariable("month") String month, @RequestParam String parmRequestSource, @RequestParam(required=false) String parmAudienceType, @RequestBody OrderRequestForm orderRequestForm) < OrderResponse orderResponse = new OrderResponse(); log.info("In getOrder3. parmRequestSource = " + parmRequestSource + " parmAudienceType = " + parmAudienceType); try < //validate JSON schema //orderService.validateMessageAgainstJSONSchema(orderRequestForm); //process order orderResponse = orderService.processOrder(orderRequestForm); orderResponse.setParmRequestSource(parmRequestSource); orderResponse.setParmAudienceType(parmAudienceType); orderResponse.setMonth(month); >catch (Exception e) < throw new OrderException("101", e.getMessage(), HttpStatus.BAD_REQUEST); >return new ResponseEntity<>(orderResponse,HttpStatus.OK); > 

The functionality has been confirmed to be operational through testing in Postman.

While using restTemplate.postForObject to call another microservice, I encountered an error. I attempted to use two different versions of the client: getOrderClient and getOrderClient2.

getOrderClient

@PostMapping(value="/getOrderClient/",produces="application/json") public OrderResponse getOrderClient( @PathVariable("month") String month, @RequestParam String parmRequestSource, @RequestParam String parmAudienceType, @RequestBody OrderRequestForm orderRequestForm) throws URISyntaxException, JsonProcessingException < RestTemplate restTemplate = new RestTemplate(); URI uri = new URI("http://localhost:51001/orders/v1/getOrder/"+month+"?parmRequestSource="+parmRequestSource+"&parmAudienceType="+parmAudienceType); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); String requestJson = new ObjectMapper().writeValueAsString(orderRequestForm); HttpEntityhttpEntity = new HttpEntity(requestJson,headers); String response = restTemplate.postForObject(uri, httpEntity, String.class); return new ObjectMapper().readValue(response, OrderResponse.class); > 

Obtain the second client’s order.

@PostMapping(value="/getOrderClient2/",produces="application/json") public OrderResponse getOrderClient2( @PathVariable("month") String month, @RequestParam String parmRequestSource, @RequestParam String parmAudienceType, @RequestBody OrderRequestForm orderRequestForm) throws URISyntaxException, JsonProcessingException < RestTemplate restTemplate = new RestTemplate(); URI uri = new URI("http://localhost:51001/orders/v1/getOrder/"+month+"?parmRequestSource="+parmRequestSource+"&parmAudienceType="+parmAudienceType); return restTemplate.postForObject(uri, orderRequestForm, OrderResponse.class); >

Both are giving same error :

The HTTP status code 400, specifically the HttpClientErrorException$BadRequest, has been encountered without a response body.

In order to enhance the solution’s visibility, @astar resolved the problem by applying @JsonProperty annotations to the model object’s properties.

Spring boot — HttpClientErrorException$BadRequest: 400, Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

Источник

Читайте также:  Use string class in java
Оцените статью