@RestControllerAdvice не работает. Я использую версию Spring boot 2.2.6. - PullRequest
0 голосов
/ 07 мая 2020
• 1000
    package com.apps.developerblog.app.ws.ui.controller;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;

    import javax.validation.Valid;

    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import com.apps.developerblog.app.ws.ui.model.request.UpdateUserRequestModel;
    import com.apps.developerblog.app.ws.ui.model.request.UserDetailsRequestModel;
    import com.apps.developerblog.app.ws.ui.model.response.UserRest;
    import com.apps.developerblog.ws.exception.UserServiceException;

    @RestController
    @RequestMapping("/users") // http://localhost
    public class UserController {
        Map<String, UserRest> users;

        @GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<UserRest> getUser(@PathVariable("userId") String userId) {

            if (true)
                throw new UserServiceException("A user serviec exception is thrown");
            if (users.containsKey(userId)) {
                return new ResponseEntity<UserRest>(users.get(userId), HttpStatus.OK);
            } else {
                return new ResponseEntity<UserRest>(HttpStatus.NO_CONTENT);
            }

        }

        /*
         * @GetMapping public String getUsers(@RequestParam(value = "page", defaultValue
         * = "2") int page,
         * 
         * @RequestParam(value = "limit") int limit,
         * 
         * @RequestParam(value = "sort", defaultValue = "desc", required = false) String
         * sort) { return "get User was called with page=" + page + " limit =" + limit +
         * " and sort=" + sort; }
         */

        @PostMapping(consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = {
                MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<UserRest> createUser(@Valid @RequestBody UserDetailsRequestModel userDetails) {
            String userId = UUID.randomUUID().toString();
            UserRest returnValue = new UserRest();
            returnValue.setEmail(userDetails.getEmail());
            returnValue.setFirstName(userDetails.getFirstName());
            returnValue.setLastName(userDetails.getLastName());
            returnValue.setUserId(userId);

            if (users == null)
                users = new HashMap<>();
            users.put(userId, returnValue);

            return new ResponseEntity<UserRest>(returnValue, HttpStatus.OK);

        }

        @PutMapping(path = "/{userId}", consumes = { MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
                        MediaType.APPLICATION_JSON_VALUE })
        public UserRest updateUser(@PathVariable String userId,
                @Valid @RequestBody UpdateUserRequestModel userDetailsRequestModel) {
            UserRest storedUserDetails = users.get(userId);
            storedUserDetails.setFirstName(userDetailsRequestModel.getFirstName());
            storedUserDetails.setLastName(userDetailsRequestModel.getLastName());
            users.put(userId, storedUserDetails);
            return storedUserDetails;
        }

        @DeleteMapping(path = "/{userId}")
        public ResponseEntity<String> deleteUser(@PathVariable String userId) {
            if (users.containsKey(userId)) {
                users.remove(userId);
                return new ResponseEntity<String>("User Deleted ", HttpStatus.OK);
            } else {
                return new ResponseEntity<String>("User Not  Deleted ", HttpStatus.NOT_FOUND);
            }

        }

    }

GlobalExceptional:
package com.apps.developerblog.ws.exception;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 *
 * @author 
 */
@RestControllerAdvice
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiErrorResponse constraintViolationException(ConstraintViolationException ex, WebRequest request) {
        return new ApiErrorResponse(500, 5001, ex.getMessage());
    }

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiErrorResponse noHandlerFoundException(Exception ex, WebRequest reques) {
        return new ApiErrorResponse(404, 4041, ex.getMessage());
    }

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }

    @ExceptionHandler(value = { NullPointerException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse nullPointerException(NullPointerException ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }

    @ExceptionHandler(value = { UserServiceException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse UserServiceException(UserServiceException ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }
}

package com.apps.developerblog.ws.exception;

/**
 * @author
 */
public class ApiErrorResponse {

    private int status;
    private int code;
    private String message;

    public ApiErrorResponse(int status, int code, String message) {
        this.status = status;
        this.code = code;
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "ApiErrorResponse{" + "status=" + status + ", code=" + code + ", message=" + message + '}';
    }
}


Error class:

package com.apps.developerblog.ws.exception;

public class UserServiceException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public UserServiceException(String message) {
        super(message);

    }

}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mobile-app-ws</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mobile-app-ws</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml/jackson-xml-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>




    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1 Ответ

0 голосов
/ 07 мая 2020

Попробуйте добавить следующий код в свой контекст, ваш вопрос очень абстрактный и неполный.

@ControllerAdvice
class StatusControllerAdvice {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> notFoundException(final RuntimeException e) {
//        return new ResponseEntity<String>("false", HttpStatus.INTERNAL_SERVER_ERROR);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

@RestController
@RequestMapping("/status")
public class StatusController {

    @GetMapping("/string")
    public String getString() {
        return "OK";
    }

    @GetMapping(value = "/file")
    public String getImage() {
        File file = new File("/home/ashish1");
        if (file.exists()) {
            return "true";
        }
        throw new RuntimeException("Invalid File");
    }
}

Как получить доступ к этому URL:

http://localhost:8080/status/file
...