1. 程式人生 > >JAVA全域性異常處理

JAVA全域性異常處理

全域性異常處理:
1.在pom中引入 : <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem-spring-web</artifactId>
            <version>${problem.spring.web.version}</version>
           </dependency>


2.編寫異常一般繼承:RuntimeException / AbstractThrowableProblem
example: 2.1)public class EntityConflictException extends RuntimeException {
    public EntityConflictException() {
    }


    public EntityConflictException(String message) {
        super(message);
    }


    public EntityConflictException(String message, Throwable cause) {
        super(message, cause);
    }
  }
  2.2)public class BadRequestException extends AbstractThrowableProblem {
    public BadRequestException(String message) {
        super(Problem.DEFAULT_TYPE, message, Status.BAD_REQUEST);
    }
}
3.編寫ExceptionHandle繼承ProblemHandling
example:
@ControllerAdvice(annotations = RestController.class)
public class SLPExceptionHandler implements ProblemHandling {


    /**
     * Post-process Problem payload to add the message key for front-end if needed
     */
    @Override
    public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
        if (entity == null || entity.getBody() == null) {
            return entity;
        }
        Problem problem = entity.getBody();
        if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
            return entity;
        }
        ProblemBuilder builder = Problem.builder()
                .withType(Problem.DEFAULT_TYPE)
                .withStatus(problem.getStatus())
                .withTitle(problem.getTitle())
                .with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());


        if (problem instanceof ConstraintViolationProblem) {
            builder
                    .with("violations", ((ConstraintViolationProblem) problem).getViolations())
                    .with("message", Problem.DEFAULT_TYPE);
            return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
        } else {
            builder
                    .withCause(((DefaultProblem) problem).getCause())
                    .withDetail(problem.getDetail())
                    .withInstance(problem.getInstance());
            problem.getParameters().forEach(builder::with);
            if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
                builder.with("message", "error.http." + problem.getStatus().getStatusCode());
            }
            return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
        }
    }


    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<Problem> handleAuthentication(AuthenticationException ex, NativeWebRequest request) {
        Problem problem = Problem.builder()
                .withType(Problem.DEFAULT_TYPE)
                .withTitle("Access Denied")
                .withStatus(Status.UNAUTHORIZED)
                .with("message", "Invalid token")
                .build();
        return create(ex, problem, request);
    }


    @ExceptionHandler(ValidateException.class)
    public ResponseEntity<String> handleValidateException(ValidateException ex) {
        ObjectNode objNode = JsonNodeFactory.instance.objectNode();
        String exMessage = ex.getMessage();
        objNode.put("message", Objects.isNull(exMessage) ? "Validation error!" : exMessage);
        return new ResponseEntity<>(objNode.toString(), HttpStatus.BAD_REQUEST);
    }


    @ExceptionHandler(EntityConflictException.class)
    public ResponseEntity<String> handleEntityConflictException(EntityConflictException ex) {
        ObjectNode objNode = JsonNodeFactory.instance.objectNode();
        objNode.put("message", ex.getMessage());
        return new ResponseEntity<>(objNode.toString(), HttpStatus.CONFLICT);
    }


    @ExceptionHandler(ExtractContentException.class)
    public ResponseEntity<String> handleExtractContentException(ExtractContentException ex) {
        ObjectNode objNode = JsonNodeFactory.instance.objectNode();
        objNode.put("message", ex.getMessage());
        return new ResponseEntity<>(objNode.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}