后端返回的异常信息必需的元素是错误信息(message)。异常的错误编码(code)可以根据业务需要进行细化(一般来说使用HTTP status code即可满足要求),某些情况下,异常可能会携带发生异常的具体数据。
package com.example.demo;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class ErrorResult {
private int code;
private String message;
private Object data;
}
ResourceNotFoundException.java
package com.example.demo.exception;
public class ResourceNotFoundException extends BizException {
// 记录业务主键
private final Object pk;
public ResourceNotFoundException(String entityName, Object pk) {
super("找不到ID为" + pk + "的" + entityName);
this.pk = pk;
}
public Object getPk() {
return pk;
}
}
package com.example.demo.controller;
import com.example.demo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/foos")
@Api(tags = "Foo CRUD服务")
public class FooController {
@Autowired
private FooService fooService;
@GetMapping("/{id}")
@ApiOperation("根据ID查询结果")
public FooDto findById(@PathVariable("id") Long id) {
Optional<FooDto> optional = fooService.findById(id);
if (optional.isPresent()) {
FooDto foo = optional.get();
if (foo.isDisabled()) {
throw new BizException("Foo is disabled");
}
return foo;
} else {
throw new ResourceNotFoundException("Foo", id);
}
}
}
GlobalExceptionHandler.java
package com.example.demo;
import com.example.demo.exception.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
public class GlobalExceptionHandler {
// 可以根据需要定义本系统的错误码
public static final int RC_RESOURCE_NOT_FOUND = 40001;
public static final int RC_UNKNOWN_ERROR = 50000;
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public ErrorResult handleResourceNotFoundException(ResourceNotFoundException e) {
return ErrorResult.builder()
.code(RC_RESOURCE_NOT_FOUND) // 可选
.message(e.getMessage())
.data(e.getPk())
.build();
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ErrorResult handleOtherException(Exception e) {
return ErrorResult.builder()
.code(RC_UNKNOWN_ERROR) // 可选
.message(e.getMessage())
.build();
}
}